Factorial Trailing Zeroes(OJ) 求其階乘尾數0的個數[1808548329]
阿新 • • 發佈:2018-12-31
問題描述:
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
問題分析:一個2和一個5相乘就會產生一個0,階乘過程中5的個數肯定會比2多
例如: 5! =(2 * 2 * 2 * 3 * 5). 所以 0個數 is 1.
11! (2 8 * 34 * 52 * 7). 所以 0個數 is 2.
問題轉化為求階乘過程中5的個數,而且注意25裡有2個5,125有三個五,所以問題變為:
count= floor(n/5) + floor(n/25) + floor(n/125) + ....
網上有一個經典寫法:
// Function to return trailing 0s in factorial of n
int findTrailingZeros(int n)
{
// Initialize result
int count = 0;
// Keep dividing n by powers of 5 and update count
for (int i=5; n/i>=1; i *= 5)
count += n/i;
return count;
}
在oj上提交會發現n =
1808548329時WA了
原因就是 i*5一直連乘時出現i = 14時,記憶體溢位(5^13
= 1220703125 < 2^31, but 5^14 = 6103515625 > 2^32)
但是 6103515625 % 2^32 = 1808548329 < 2 ^31,即1808548329 為合理輸入
解決辦法:
int trailingZeroes(int n) {
int count = 0;
for(int i = 5; n/i >= 1;)
{
count += n/i;
n /= 5;
}
return count;
}
---附加-----2015年加油!注意細節,關注思想。
一直都斷斷續續,但是依然繼續,我依然很菜,但是我依然堅持成長。
Trust in the Load with all your heart and learn not on your own understanding;
in all your ways acknowledge him, and he will make your paths straight. -[Proverbs 3:5-6]