http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1721
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 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
题目:输入两个整数,m和n求出最大的整数k使得m^k是n!的约数。
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
using namespace std;
const int N=10005;
bool prime[N];
int p[N];
int k,cnt;
int pri[N],num[N];
void isprime()//筛选出所需范围内所有的素数
{
k=0;
memset(prime,true,sizeof(prime));
for(int i=2;i<N;i++)
{
if(prime[i])
{
p[k++]=i;
for(int j=i+i;j<N;j+=i)
prime[j]=false;
}
}
}
void divide(int n)// 将整数n进行素因子分解素因子保存在pri[]素组中,而该素因子对应的幂指数保存在num[]素组中。
{
int t=(int)sqrt(1.0*n);//若n不是素数那么最大的素因子只可能小于或等于根号n,优化省时
cnt=0;
for(int i=0;p[i]<=t;i++)
{
if(n%p[i]==0)
{
pri[cnt]=p[i];
int a=0;
while(n%p[i]==0)
{
a++;
n/=p[i];
}
num[cnt]=a;
cnt++;
}
}
if(n>1)//如果此时n还没被变为1,就说明n本身是一个素数
{
pri[cnt]=n;
num[cnt]=1;
cnt++;
}
}
int cal(int n,int p)//阶乘的素因子分解
{
int ans=0;
while(n)
{
ans+=n/p;
n/=p;
}
return ans;
}
void work(int m,int n)
{
divide(m);
int ans=99999999;
for(int i=0;i<cnt;i++)//若m的素因子在n!中都有则一定有n!可以整除m,反之就不行
{
int b=cal(n,pri[i]);
int tmp=b/num[i];
if(ans>tmp)//ans的最大取值总是等于n!和m对应素因子商的最小值
ans=tmp;
}
if(ans==0)
puts("Impossible to divide");
else
printf("%d\n",ans);
}
int main()
{
isprime();
int T,n,m,tt=1;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&m,&n);
printf("Case %d:\n",tt++);
work(m,n);
}
return 0;
}