Again Prime? No time.
Input: standard input
Output: standard output
Time Limit: 1 second
The problem statement is very easy. Given a number n you have to determine the largest power of m, not necessarily prime, that divides n!.
Input
The input file consists of several test cases. The first line in the file is the number of cases to handle. The following lines are the cases each of which contains two integers m (1<m<5000) and n (0<n<10000). The integers are separated by an space. There will be no invalid cases given and there are not more that 500 test cases.
Output
For each case in the input, print the case number and result in separate lines. The result is either an integer if mdivides n! or a line "Impossible to divide" (without the quotes). Check the sample input and output format.
Sample Input
2
2 10
2 100
Sample Output
Case 1:
8
Case 2:
97
解题报告:简单来说就是求最大的m的几次方,使其能整除n!。
很容易想到对m因式分解,对于每个素因子,计算n!最多能提供的数量。如果不够,说明无法整除;否则统计最小的倍数,即为结果。代码如下:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; int cas=1; int check(int n,int m) { int ans=~0U>>1; for(int i=2;i*i<=m;i++) if(m%i==0) { int t=0; while(m%i==0) m/=i,t++; int nn=n; int tt=0; while(nn) nn/=i,tt+=nn; if(tt<t) return -1; ans=min(ans,tt/t); } if(m>1) { int i=m; int t=1; int nn=n; int tt=0; while(nn) nn/=i,tt+=nn; if(tt<t) return -1; ans=min(ans,tt/t); } return ans; } void work() { int n,m; scanf("%d%d",&m,&n); int ans=check(n,m); printf("Case %d:\n", cas++); if(ans==-1) puts("Impossible to divide"); else printf("%d\n",ans); } int main() { int T; scanf("%d",&T); while(T--) work(); }
Problem setter: Anupam Bhattacharjee, CSE, BUET
Thanks to Shabuj for checking and Adrian for alternate solution.