Factorial

You task is to find minimal natural number N, so that N! contains exactly Q zeroes on the trail in decimal notation. As you know N! = 1*2*…*N. For example, 5! = 120, 120 contains one zero on the trail.

Input

One number Q written in the input (0<=Q<=10^8).

Output

Write “No solution”, if there is no such number N, and N otherwise.

Sample Input

2

Sample Output
10

题意:计算满足N!后面有Q个0的最小N

由于N!有可能是一个很大的数,所以我们不能直接计算N!的值,由于0是有2和5 相乘得到的,我们只要计算2和5有多少就行了。然而2的值远远多于5的值,切记有一些数可能含有多个5(如:25,50,75,100都可以贡献两个5)。我们可以用二分查找(不然会TLE),从0到5*Q查找满足题意的最小值(一定是5的倍数)

最重要的一点:当Q为0的时候,要输出1,而不是0(难道0不是自然数吗(ಥ _ ಥ),因为这一点WA了好几次)

#include <stdio.h>
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
long long Q;
bool flag;

int fun(int n)
{
    int ans = 0;
    while(n)
    {
        ans += n/5;
        n /= 5;
    }
    return ans;
}

int search()
{
    long long left = 0, right = 5*Q, mid, t;
    while(left <= right)
    {
        mid = (left + right) / 2;
        if (fun(mid) == Q)
        {
            flag = true;
            t = mid/5;
            mid = t *5;
            return mid;
        }
        if (fun(mid) > Q)
        {
            right = mid - 1;
        }
        else
        {
            left = mid + 1;
        }
    }
}

int main()
{
#ifndef ONLINE_JUDGE
    //freopen("1.txt", "r", stdin);
#endif
    long long i, ans, t;
    while(~scanf("%I64d", &Q))
    {
        if (!Q)
        {
            cout << "1\n";
            continue;
        }
        flag = false;
        ans = search();
        if(flag)
            cout << ans << endl;
        else
            cout << "No solution\n";
    }
    return 0;
} 

你可能感兴趣的:(Factorial)