File tree Expand file tree Collapse file tree 1 file changed +59
-0
lines changed
Expand file tree Collapse file tree 1 file changed +59
-0
lines changed Original file line number Diff line number Diff line change 1+ package easy ;
2+
3+ import java .math .BigInteger ;
4+
5+ public class FactorialTrailingZeroes172 {
6+
7+ public static int trailingZeroesNonOptimal (int n ) {
8+
9+ BigInteger factN = factorial (n );
10+
11+ int count = 0 ;
12+
13+ while (factN .mod (BigInteger .TEN ).equals (BigInteger .ZERO )) {
14+ factN = factN .divide (BigInteger .valueOf (10 ));
15+ count ++;
16+ }
17+
18+ return count ;
19+ }
20+
21+ // iterative approach to find factorial
22+ private static BigInteger factorial (int n ) {
23+ if (n == 0 || n == 1 )
24+ return BigInteger .ONE ;
25+
26+ BigInteger ans = BigInteger .ONE ;
27+
28+ for (int i = 2 ; i <= n ; i ++) {
29+ ans = ans .multiply (BigInteger .valueOf (i ));
30+ }
31+
32+ return ans ;
33+ }
34+
35+ // recursive approach to find factorial
36+ private static BigInteger factorialRec (int n ) {
37+ if (n == 0 || n == 1 )
38+ return BigInteger .ONE ;
39+
40+ return BigInteger .valueOf (n ).multiply (factorialRec (n - 1 ));
41+ }
42+
43+ // optimal code - accepted Oms solution
44+ public static int trailingZeroes (int n ) {
45+
46+ int count = 0 ;
47+
48+ while (n > 0 ) {
49+ n = n / 5 ;
50+ count = count + n ;
51+ }
52+
53+ return count ;
54+ }
55+
56+ public static void main (String [] args ) {
57+ System .out .println (trailingZeroes (10000 ));
58+ }
59+ }
You canβt perform that action at this time.
0 commit comments