-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path172.factorial-trailing-zeroes.go
77 lines (71 loc) · 1.71 KB
/
172.factorial-trailing-zeroes.go
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* @lc app=leetcode id=172 lang=golang
*
* [172] Factorial Trailing Zeroes
*
* https://leetcode.com/problems/factorial-trailing-zeroes/description/
*
* algorithms
* Easy (37.73%)
* Likes: 918
* Dislikes: 1151
* Total Accepted: 215.5K
* Total Submissions: 570.4K
* Testcase Example: '3'
*
* Given an integer n, return the number of trailing zeroes in n!.
*
* Example 1:
*
*
* Input: 3
* Output: 0
* Explanation: 3! = 6, no trailing zero.
*
* Example 2:
*
*
* Input: 5
* Output: 1
* Explanation: 5! = 120, one trailing zero.
*
* Note: Your solution should be in logarithmic time complexity.
*
*/
// https://leetcode.com/problems/factorial-trailing-zeroes/discuss/52367/my-explanation-of-the-logn-solution
// 10 is the product of 2 and 5. In n!, we need to know how many 2 and 5, and the number of zeros is the minimum of the number of 2 and the number of 5.
//Since multiple of 2 is more than multiple of 5, the number of zeros is dominant by the number of 5.
// @lc code=start
func trailingZeroes(n int) int {
return trailingZeroes2(n)
}
// The ZERO comes from 10.
// The 10 comes from 2 x 5
// And we need to account for all the products of 5 and 2. likes 4×5 = 20 ...
// So, if we take all the numbers with 5 as a factor, we'll have way more than enough even numbers to pair with them to get factors of 10
func trailingZeroes3(n int) int {
retVal := 0
for n > 0 {
retVal += n / 5
n /= 5
}
return retVal
}
func trailingZeroes2(n int) int {
if n == 0 {
return 0
}
return n/5 + trailingZeroes2(n/5)
}
// Time Limit Exceeded
func trailingZeroes1(n int) int {
retVal := 0
for i := 1; i <= n; i++ {
for j := i; j%5 == 0; {
retVal++
j /= 5
}
}
return retVal
}
// @lc code=end