MAGMA Interview Question
Software Engineer / DevelopersEach occurence of 5 with an even number gives the 0 at the end.
So, in 100!, first find the occurences of 5 . i.e. how many powers of 5 are contained in 100!
Powers of 5 in 100! = 100/5 + 100/(5^2) + 100/(5^3) + .....
= 20 + 4 + 0..
= 24
SO the ans is 24.
@avatarz: 100! = 9.33262154 × 10 ^ 157 is the way of representing the final ans but it does not provide the 0s at the end.
For ex: 1930000 can be written as 1.93 * 10^6 or 19.3 * 10^5 or 193 * 10^4.... it's not giving the no. of 0s at the end.
the number of 0s in n! is the power of 5 in the prime factorization of n
n! = 2^k1 * 3^k2 * 5^k3 * 7^k4 * ...
to get k3, one will have to:
k3 = 0
for i=5:n
j = i
while j % 5 == 0
k3++
j /= 5
return k3
Time complexity:
O(n) = sum over i (log_5 i) <= n * log_5(n) = O(n * log_5 n)
log_5 i = log in base 5 of i
Each occurence of 5 with an even number gives the 0 at the end.
So, in 100!, first find the occurences of 5 . i.e. how many powers of 5 are contained in 100!
Powers of 5 in 100! = 100/5 + 100/(5^2) + 100/(5^3) + .....
= 20 + 4 + 0..
= 24
SO the ans is 24.
@avatarz: 100! = 9.33262154 × 10 ^ 157 is the way of representing the final ans but it does not provide the 0s at the end.
For ex: 1930000 can be written as 1.93 * 10^6 or 19.3 * 10^5 or 193 * 10^4.... it's not giving the no. of 0s at the end.
A function E(p){n!}=[n/p]+[n/p^2]+[n/p^3]+.... where (p) is the prime factor. Eg: 10 = 2, 5. Prime factor. So, P =2,5.The soln is as follows: Prime factors of 10=2*5 and E(2){50!}=[50/2]+[50/4]+[50/8]+[50/16]+[… or E(2){50!}=47 and E(5){50!}=[50/5]+[50/25]+[50/125] or E(5){50!}=12. Then E(10){50!}=the number of zeros in 50!=min of (47,12). Hence number of zeros in 50! is 12.
A function E(p){n!}=[n/p]+[n/p^2]+[n/p^3]+.... where (p) is the prime factor. Eg: 10 = 2, 5. Prime factor. So, P =2,5.The soln is as follows: Prime factors of 10=2*5 and E(2){50!}=[50/2]+[50/4]+[50/8]+[50/16]+[… or E(2){50!}=47 and E(5){50!}=[50/5]+[50/25]+[50/125] or E(5){50!}=12. Then E(10){50!}=the number of zeros in 50!=min of (47,12). Hence number of zeros in 50! is 12.
use formula
- sandy880 February 20, 2011no=(a/5^1)+(a/5^2)+.......
where no=number of zero
a=no. for which no.of zeros is to be calculated
take only int value of no.