1. 程式人生 > >SGU 154 Factorial(數論+二分)

SGU 154 Factorial(數論+二分)

Description
求最小的整數n使得n!的值後面有q個0
Input
一個整數q(0<=q<=10^8)
Output
滿足條件的最小的正整數n,如果不存在則輸出No solution
Sample Input
2
Sample Output
10
Solution
n!後面0的個數等於n!的質因子分解形式中5的冪指數,即為[n/5]+[[n/5]/5]+…,所以n最多為5*10^8,二分n即可
Code

#include<cstdio>
#include<iostream>
using namespace std;
#define maxn 11111
#define INF 0x3f3f3f3f int count(int n) { int ans=0; while(n) { ans+=n/5; n/=5; } return ans; } void solve(int n) { int l=0,r=INF; while(l<=r) { int mid=(l+r)>>1; int temp=count(mid); if(temp>=n)r=mid-1; else if(temp<n)l=mid+1
; } if(count(l)==n)printf("%d\n",l); else printf("No solution\n"); } int main() { int n; scanf("%d",&n); if(n==0)printf("1\n"); else solve(n); return 0; }