How to check if a number is a power of 5?
I could think of below algorithm. Is there way to improve it? Any mathematical trick?
You don't need to look at individual digits, you can just do it like this:
n = (int)(log(x) / log(5)); // get n = log5(x), truncated to integer
if (pow(5, n) == x) // test to see whether x == 5^n
// x is a power of 5
LIVE DEMO
There are only few power of five that fit in int/long range, so you just need to generate all of them and check one by one (less than 60 numbers), using a HashSet will have O(1) time complexity
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With