uva 10780Again Prime? No Time.

来源:互联网 发布:网易新闻ios源码 编辑:程序博客网 时间:2024/05/29 14:51

原题:
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 <bits/stdc++.h>using namespace std;int p[10001];bool tag[100010];void get_prime(){    int cnt=0;    for(int i=2;i<10010;i++)    {        if(!tag[i])            p[cnt++]=i;        for(int j=0;j<cnt&&p[j]*i<10010;j++)        {            tag[i*p[j]]=1;            if(i%p[j]==0)                break;        }    }}void fac_decomposition(int x,int v[]){    for(int i=2;i<=x;i++)    {        int k=0;        int t=i;        while(t>1)        {            if(t%p[k]==0)            {                t/=p[k];                v[p[k]]++;            }            else                k++;        }    }}void decomposition(int x,int v[]){    int k=0;    while(x>1)    {        if(x%p[k]==0)        {            x/=p[k];            v[p[k]]++;        }        else            k++;    }}int mfac[10001],nfac[10001];int main(){    ios::sync_with_stdio(false);    get_prime();    int t,n,m,k=1;    cin>>t;    while(t--)    {        memset(mfac,0,sizeof(mfac));        memset(nfac,0,sizeof(nfac));        cin>>m>>n;        fac_decomposition(n,nfac);        decomposition(m,mfac);        int flag=0;        int ans=INT_MAX;        for(int i=2;i<=5000;i++)        {            if(mfac[i]>nfac[i])            {                flag=1;                break;            }            if(mfac[i]!=0)            {                ans=min(ans,nfac[i]/mfac[i]);            }        }        cout<<"Case "<<k++<<":"<<endl;        if(!flag)            cout<<ans<<endl;        else            cout<<"Impossible to divide"<<endl;    }    return 0;}

解答:
很简单的入门题目,首先筛个素数表,然后使用唯一分解定理把n!和m分解出来存在nfac和mfac当中。如果m当中存在的质因子而n!当中没有那么n!肯定除不开m,就更别提m^k了。现在设Pi是n!和m都有的质因子,设Pi^x和Pi^y,x是n!当中Pi的指数幂,y是m的Pi的指数幂,用x/y取整得到k值,枚举Pi,找到最小的那个k就是答案。

0 0
原创粉丝点击