-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathFactorialTrailingZeroes172.java
59 lines (41 loc) · 1.08 KB
/
FactorialTrailingZeroes172.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package easy;
import java.math.BigInteger;
public class FactorialTrailingZeroes172 {
public static int trailingZeroesNonOptimal(int n) {
BigInteger factN = factorial(n);
int count = 0;
while (factN.mod(BigInteger.TEN).equals(BigInteger.ZERO)) {
factN = factN.divide(BigInteger.valueOf(10));
count++;
}
return count;
}
// iterative approach to find factorial
private static BigInteger factorial(int n) {
if (n == 0 || n == 1)
return BigInteger.ONE;
BigInteger ans = BigInteger.ONE;
for (int i = 2; i <= n; i++) {
ans = ans.multiply(BigInteger.valueOf(i));
}
return ans;
}
// recursive approach to find factorial
private static BigInteger factorialRec(int n) {
if (n == 0 || n == 1)
return BigInteger.ONE;
return BigInteger.valueOf(n).multiply(factorialRec(n - 1));
}
// optimal code - accepted Oms solution
public static int trailingZeroes(int n) {
int count = 0;
while (n > 0) {
n = n / 5;
count = count + n;
}
return count;
}
public static void main(String[] args) {
System.out.println(trailingZeroes(10000));
}
}