Microsoft Interview Question

how many zeros are there in 100!

Interview Answers

Anonymous

Jan 31, 2012

The question asks for the number of 0s in the decimal representation of 100!, not the number of trailing 0s, which is quite easy to find.

2

Anonymous

Feb 17, 2012

I think the interviewer actually asked for the number of trailing 0's and if that is the case, the solution listed above is far than optimal. :) The idea is good though. We should start again with a couple of observations: - 0's are generated by 2*5 indeed - we do not need to count the 2's because for every number the number of 2's is > number of 5's, so only how many 5's we have to 100 we need to count. The solution would be as follows: int numberOfTrailingZeros(int factorial) { int result = 0; while (factorial >= 5) { result += (factorial\5); factorial \= 5; } return result; }

Anonymous

Jan 26, 2012

not only the zeros in the end.

Anonymous

Jan 29, 2012

This is in fact a complicated math problem. What you want to do is to find how many trailing ceros does 100! Have with out having to Calculate the number. We know that the only way to get a trailing cero is to multiply a number by 10, or what would be the same, to miltiply it by 5 and 2. So what you want to do here is very easy, you need to find how many 2 and fives are there from 2-100. At last you would just have to check if you have more 2s or more 5s because you want to return only the smaller number. Your code would look something like this: two = five = 0; For(i=0;i<101;i++) while(i%2==0) two++; i=i/2; while(i%5==0) five++; i=i/5; if(two

Anonymous

Jan 29, 2012

here's the code for my previous solution, it's in c++. #include using namespace std; int main(){ int two=0, five=0, i; int num; for(i=2;i<101;i++) { num=i; while(num%2==0) { two++; num=num/2; } while(num%5==0) { five++; num=num/5; } } if(two