Description: Write an algorithm which computes the number of trailing zeros in n factorial.
Thought: 0 comes from 5 and 2, because in n factorial there will be always enough 2....so every 5 will result in a zero.(25 is 5*5 so result in 2 zeros)
Code:
public static int numZeros(int num) {
int count = 0;
for (int i = 5; num / i > 0; i = i * 5) {
count = count + num / i;
}
return count;
}
Explanation:
The first loop we count the first column of 5s in the right side, the second loop count the second column of 5s....
5 5
10 5
15 5
20 5
25 55
30 5
35 5
40 5
45 5
50 55
55 5
.. ...
75 55
No comments:
Post a Comment