Number of trailing zeros of N in Java

The challenge

Write a program that will calculate the number of trailing zeros in a factorial of a given number.

N! = 1 * 2 * 3 * ... * N

Be careful 1000! has 2568 digits…

For more info, see: http://mathworld.wolfram.com/Factorial.html

Examples

zeros(6) = 1 // 6! = 1 * 2 * 3 * 4 * 5 * 6 = 720 --> 1 trailing zero zeros(12) = 2 // 12! = 479001600 --> 2 trailing zeros
Code language: Java (java)

The solution in Java code

Option 1:

public class Solution { public static int zeros(int n) { int res = 0; for (int i = 5; i <= n; i *= 5) { res += n / i; } return res; } }
Code language: Java (java)

Option 2:

public class Solution { public static int zeros(int n) { if(n/5 == 0) return 0; return n/5 + zeros(n/5); } }
Code language: Java (java)

Option 3:

public class Solution { public static int zeros(final int n) { return (n < 5) ? 0 : (n / 5) + zeros(n / 5); } }
Code language: Java (java)

Test cases to validate our solution

import org.junit.Test; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; public class SolutionTest { @Test public void testZeros() throws Exception { assertThat(Solution.zeros(0), is(0)); assertThat(Solution.zeros(6), is(1)); assertThat(Solution.zeros(14), is(2)); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments