1. 程式人生 > >UVA - 10780 Again Prime? No Time. (質因子分解)

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;
}