Skip to content

Instantly share code, notes, and snippets.

@clementi
Created June 19, 2011 03:51
Show Gist options
  • Save clementi/1033739 to your computer and use it in GitHub Desktop.
Save clementi/1033739 to your computer and use it in GitHub Desktop.
Calculate the Number of Trailing Zeros in a Factorial
public class Solution {
public static void main(String[] args) {
System.out.println(countTrailingZerosOfFactorial(100));
}
private static final int countTrailingZerosOfFactorial(final int n) {
int count = 0;
for (int factor = 5; factor <= n; factor += 5)
count += countFives(factor);
return count;
}
private static final int countFives(int factor) {
if (!divides(5, factor))
return 0;
return 1 + countFives(factor / 5);
}
private static final boolean divides(final int d, final int n) {
return n % d == 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment