Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to find the largest power of 10 smaller than x

Is there any fast way to find the largest power of 10 smaller than a given number?

I'm using this algorithm, at the moment, but something inside myself dies anytime I see it:

10**( int( math.log10(x) ) ) # python
pow( 10, (int) log10(x) )   // C

I could implement simple log10 and pow functions for my problems with one loop each, but still I'm wondering if there is some bit magic for decimal numbers.

like image 678
peoro Avatar asked Dec 22 '10 21:12

peoro


People also ask

How do you find the greatest power of a factorial?

If we are asked to find the highest power of a number 'n' in a factorial, where n is a prime number, we can directly divide the factorial number by 'n' (and possible powers of 'n') to find the instances of 'n', and subsequently the highest power of 'n'.

How do you find the largest power of a prime number?

Similarly, P(N,r)=N! (N−r)!. Hence, the largest power of a prime, dividing P(N,r) is given by sp(N!)


1 Answers

An alternative algorithm is:

i = 1;
while((i * 10) < x)
    i *= 10;
like image 92
Anon. Avatar answered Sep 18 '22 15:09

Anon.