UVA - 10780 Again Prime? No Time. (质因子分解)

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,求n!中最多有多少个m相乘。

思路:因为用到质因数分解,所以需要先打一个素数表,然后对于每一个素数,对m和n!进行质因数分解,分别求出m和n!中最多有多少个prime[i]相乘,然后将两个数量相除,找到最小的就是答案。

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int visit[10005];
int prime[10005];
int num=1;
void sushu()//打素数表
{

    memset(visit,0,sizeof(visit));
    for(int i=2;i<10005;i++)
    {
        if(!visit[i])
            prime[num++]=i;
        for(int j=i*i;j<10005;j=j+i)
            visit[j]=1;
    }
}
int main()
{

    sushu();
    int t;
    int m,n;
    scanf("%d",&t);
//    for(int i=1;i<100;i++)
//        cout<<prime[i]<<" ";
    for(int ti=1;ti<=t;ti++)
    {
       scanf("%d%d",&m,&n);
        int minn=0x3f3f3f3f;
        for(int i=1;m>1&&i<num;i++)//分别求m和n对质因数整除的次数。
        {
            int l=0;
            while(m%prime[i]==0)
            {
                m=m/prime[i];
                l++;
            }
            if(l!=0)
            {
                int c=n;
                int maxn=0;

                 //求n!里某个质因数的个数,比如是2的话,那么只要计算n/2+n/4+n/8...的个数就行了,可以这么想没隔2个数就有一个2,然后是4...
                while(c!=0)//求n!中某个质因数个数。
                {

                    c=c/prime[i];
                    maxn=maxn+c;


                }


                if(minn>maxn/l)//找出n!中某个质因数出现的个数与m的质因数分解中对应质因数出现的个数相除,除数最小的就是答案。
                    minn=maxn/l;
            }

        }
        if(minn!=0&&minn!=0x3f3f3f3f)
            printf("Case %d:\n%d\n",ti,minn);
        else
            printf("Case %d:\nImpossible to divide\n",ti);
    }
    return 0;
}


 

猜你喜欢

转载自blog.csdn.net/zhouchenghao123/article/details/84034713