A tiny bit of numerical experimentation gives me that the first few $n$ where the first digit of $2^n$ is equal to the first digit of $5^n$ are
$$
5,15,78,88,98,108,118,181,191,201,211,274,284,294,304.
$$
In all cases such first digit is a 3. I don't know how to prove the general fact, though. It looks like one should exploit the fact that $2^n5^n=10^n$, but since every digit is possible, it is not obvious to me how to approach a proof.
As for your program, you are using math.pow
, which uses double arithmetic, and casting to an int
. This makes your program start to fail when i=14
. That's when $5^{14}=6,103,515,625$, which is already greater than the highest possible int
which is $2,147,483,647$. What Java is doing (which I personally don't think is very nice) is just give you back $2,147,483,647$; that's why your program is incorrectly giving every single first digit for $5^n$, $n\geq14$, as $2$. Here is your program modified to work with double
public class blackadd
{
public static void main(String[] args)
{double m,n;
long startTime = System.nanoTime();
int h=0,l=0;
for(int i=1;i<=440;i++)
{n= Math.pow(2,i);
m= Math.pow(5,i);
while(n>=1)
{h=(int)(n - 10 * Math.floor(n / 10));
n=n/10;
}
while(m>=1)
{l=(int)(m - 10 * Math.floor(m / 10));
m=m/10;
}
System.out.println(i+": "+h+" -- "+l);
if(l==h)
System.out.println("\n"+"-------"+i);
}
long endTime = System.nanoTime();
long totalTime = (endTime - startTime) / 1000000;
System.out.println(totalTime);
}
}
This should work fine until $n=541$, more or less, which is where $5^n$ reaches the greatest number than can be expressed as a double. Note that %
does not work with doubles, so I had to change the way to calculate the digits. I run the program up to $i=440$ because beyond that the platform I was using (codingground) failed; not sure if it is a Java or platform thing.
As a general comment, you would usually not want to use Math.pow
to calculate powers of integers, in particular when you are using all the powers through a loop like here. You can initialize n=1
and multiply it by 2 on every iteration. I didn't put this in the code because in this case to extract the digit from a double is harder than to extract the digit from an integer as you are doing. For a double the best way I know is to do
h = Math.floor(n / Math.pow(10,Math.floor(Math.log10(n))))
,
which is not particularly efficient with four calls to the Math library.
int
) have strictly defined limits. See docs.oracle.com/javase/tutorial/java/nutsandbolts/…. $\endgroup$