Created
June 19, 2011 03:51
-
-
Save clementi/1033739 to your computer and use it in GitHub Desktop.
Calculate the Number of Trailing Zeros in a Factorial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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