求最大k使m^k是n!的约束, 分解m的质因子,然后求质因子的最小幂。最小幂就是要求的最大k
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 m divides 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
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<cmath>
using namespace std;
#define MAXN 10110
bool vis[MAXN];
int prime[MAXN],c;
void sieve(int n)
{
int m=(int)sqrt(n*1.0+0.5);
memset(vis,0,sizeof(vis));
for(int i=2;i<=m;i++) if(!vis[i])
for(int j=i*i;j<=n;j+=i) vis[j]=1;
}
int gen_primes(int n)
{
sieve(n);
c=0;
for(int i=2;i<=n;i++) if(!vis[i])
prime[c++]=i;
return c;
}
int cnt(int p,int n)
{
int ans=0;
for(int i=p;i<=n;i*=p)
ans+=(n/i);
return ans;
}
int main()
{
gen_primes(10010);
int n,m,k,t,cs=1;
cin>>t;
while(t--)
{
cin>>m>>n;
cout<<"Case "<<cs++<<":"<<endl;
int ans=0x3fffff;
int k,i=0;
while(m>1)
{
if(m%prime[i]==0)
{
int tp=cnt(prime[i],n);
m/=prime[i];k=1;
while(m%prime[i]==0) //分解质因子之后,单个质因子可能出现多次注意
{
k++;
m/=prime[i];
}
ans=min(tp/k,ans);
}
i++;
}
if(ans)
cout<<ans<<endl;
else
cout<<"Impossible to divide"<<endl;
}
return 0;
}