Question

I could just use division and modulus in a loop, but this is slow for really large integers. The number is stored in base two, and may be as large as 2^8192. I only need to know if it is a power of ten, so I figure there may be a shortcut (other than using a lookup table).

Was it helpful?

Solution

If your number x is a power of ten then

x = 10^y

for some integer y, which means that

x = (2^y)(5^y)

So, shift the integer right until there are no more trailing zeroes (should be a very low cost operation) and count the number of digits shifted (call this k). Now check if the remaining number is 5^k. If it is, then your original number is a power of 10. Otherwise, it's not. Since 2 and 5 are both prime this will always work.

OTHER TIPS

Let's say that X is your input value, and we start with the assumption.

X = 10 ^ Something

Where Something is an Integer.

So we say the following:

log10(X) = Something.

So if X is a power of 10, then Something will be an Integer.

Example

int x = 10000;
double test = Math.log10(x);

if(test == ((int)test))
    System.out.println("Is a power of 10");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top