lightoj-1138-Trailing Zeroes (III) -二分查找

题目传送门:https://vjudge.net/problem/LightOJ-1138



题意:给你一个数字,这个数字代表N!后面有几个0。给出这个数字,计算N的值。

解题思路:
任何质因数都可以写成素数相乘的形式。所以计算一个数的阶乘后面几个0,只需计算这个数包含多少5即可。


ac代码;

#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <string>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <map>
#include <set>
#define inf 0x3f3f3f3f
#define N 500000000
typedef long long ll;
using namespace std;
 
int ok(int x)
{
    int sum = 0;
    while(x)
    {
        sum = sum + x/5;
        x /= 5;
    }
    return sum;
}
 
int main()
{
    int T;
    scanf("%d", &T);
    for(int i = 1; i <= T; i++)
    {
        int n;
        scanf("%d", &n);
 
        int l = 0, r = N, mid;
        while(l <= r)
        {
            mid = (l + r) /2;
            int b = ok(mid);
            if(b >= n)
            {
                r = mid-1;
            }
            else
            {
                l = mid+1;
            }
        }
        if(ok(l) == n)
            printf("Case %d: %d\n", i, l);
        else
            printf("Case %d: no\n", i);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/newproblems/article/details/77600107
今日推荐