Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if number is summation of powers of 5 [closed]

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?

  1. First check if last digit is 5.
  2. If last digit is 5; divide it by 5.
    If result of division is 1, then number is power of 5.
    Else check if division result itself is power of 5 (i.e. go to step 1 with result as number).
like image 889
Kaushik Lele Avatar asked Nov 11 '14 10:11

Kaushik Lele


2 Answers

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

like image 131
Paul R Avatar answered Nov 15 '22 07:11

Paul R


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

like image 32
Pham Trung Avatar answered Nov 15 '22 07:11

Pham Trung