求一個數階乘的後面連續0的個數

對於一個數n的階乘 n! ,計算其後面有幾個連續的零。

  我們知道,10 = 2 * 5。每一個 2 與一個 5 相乘,結果就增加一個零。所以求 n! 後面的連續零的個數,其實就是求其中相乘的數含有因子每對因子 2 與 5  的個數。又因爲從1到某個數,所含 2 的個數比 5 多,所以問題就可以進一步簡化到求含有因子5的個數。
 
  JAVA實現代碼如下:
Code:
  1. static int zeroCount ( int n) {  
  2.     int counter = 0;  
  3.     forint i = 5,m; i <= n; i += 5) {  
  4.         m = i;  
  5.         while ( m % 5 == 0) {  
  6.             counter++;  
  7.             m /= 5;  
  8.         }  
  9.     }  
  10.     return counter;  
  11. }  
 進一步優化算法:
Code:
  1. static int zeroCount ( int n) {    
  2.     int counter = 0;    
  3.     while ( n >= 5) {    
  4.         n /= 5;  
  5.         counter += n;  
  6.     }    
  7.     return counter;    
  8. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章