Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Counting trailing 0s of n! It is not very hard to figure out how to count it - simply count how many 5s. Since even numbers are always more than 5s, we don't have to consider even numbers.

But counting 5, is tricky. Naive method is quite slow - I got 12+s for 1000000000. And after reading below article, I got 0.04s. The former counts individually, duplicated; but the latter counts smart:
http://en.wikipedia.org/wiki/Trailing_zeros#Factorial

#include <iostream>
#include <ctime>
using namespace std;


int main() 
{
    int cnt; cin >> cnt;    
    if(cnt == 0) return 0;
    
    while(cnt --)
    {
        unsigned long long n; cin >> n;        
        unsigned cnt = 0;
     
        for (int d = 5; d <= n; d *= 5) {
            cnt += n / d;
        }
        cout << cnt << endl;
    }
    return 0;
} 
View Code

 

posted on 2014-02-04 12:54  Tonix  阅读(161)  评论(0编辑  收藏  举报