国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Leetcode: Factorial Trailing Zeroes

2019-11-14 22:31:11
字體:
來源:轉載
供稿:網友
Leetcode: Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!.Note: Your solution should be in logarithmic time complexity.

Naive方法:A simple method is to first calculate factorial of n, then count trailing 0s in the result (We can count trailing 0s by repeatedly dividing the factorial by 10 till the remainder is 0). 但這樣做的顯著缺點是:can cause overflow for a slightly bigger numbers as factorial of a number is a big number (See factorial of 20 given in above examples).

轉自GeeksforGeeks的想法:The idea is to considerPRime factorsof a factorial n. A trailing zero is always produced by prime factors 2 and 5. If we can count the number of 5s and 2s, our task is done. Consider the following examples.

n = 5:There is one 5 and 3 2s in prime factors of 5! (2 * 2 * 2 * 3 * 5). So count of trailing 0s is 1.

n = 11:There are two 5s and eight 2s in prime factors of 11! (28* 34* 52* 7). So count of trailing 0s is 2.

我們會發現:the number of 2s in prime factors is always more than or equal to the number of 5s. So if we count 5s in prime factors, we are done.

How to count total number of 5s in prime factors of n!?A simple way is to calculate floor(n/5).

問題轉化為求階乘過程中質因子5的個數,但是要注意25能提供2個5,125能提供3個5....

所以,count=floor(n/5) + floor(n/25) + floor(n/125) + ....

 1 public class Solution { 2     public int trailingZeroes(int n) { 3         int count = 0; 4         for (int i=5; (n/i)>=1;) { 5             count += n / i; 6             n /= 5; 7         } 8         return count; 9     }10 }

最開始我的寫法是:

 1 // Function to return trailing 0s in factorial of n 2 int findTrailingZeros(int  n) 3 { 4     // Initialize result 5     int count = 0; 6   7     // Keep dividing n by powers of 5 and update count 8     for (int i=5; n/i>=1; i *= 5) 9           count += n/i;10  11     return count;12 }

在oj上提交會發現n = 1808548329時出錯了,期望答案是452137076,實際答案是452137080

原因就是 i*5一直連乘時出現i = 5^14時,內存溢出(5^13 = 1220703125 < 2^31, but 5^14 = 6103515625 > 2^32)

Integer overflow之后會wrap around, 即Integer.MAX_VALUE + 1會成為Integer.MIN_VALUE, 詳見Why Integer overflows wrap around

6103515625 wrap around之后 為正的1808548329-1 = 1808548328

原因是6103515625 % 2^32 = 1808548329 < 2 ^31,即 i 比32位Integer(共2^32)多出1808548329個數, 為 1808548328,又可以再進一次for 循環(本不應該進的)。所以答案偏大

解決辦法:用除法代替乘法,用n / 5代替 i * 5,防止overflow,如最上面那段code所示


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 新巴尔虎左旗| 贵定县| 阿坝县| 清原| 西吉县| 海口市| 察雅县| 吉木萨尔县| 阜新市| 长岛县| 龙山县| 孝昌县| 襄城县| 东乡县| 兰溪市| 乐亭县| 鄢陵县| 门源| 宁波市| 墨玉县| 正蓝旗| 平武县| 汪清县| 顺昌县| 东兰县| 鄯善县| 成安县| 灵武市| 平谷区| 涞源县| 扎囊县| 宁德市| 曲阳县| 夹江县| 乌海市| 澄迈县| 黄梅县| 张家港市| 冕宁县| 廉江市| 眉山市|