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

本文介绍了一种算法,用于解决给定一个数n,如何找出n!中包含的某个数m的最大幂次的问题。通过预处理素数表,对m和n!进行质因数分解,比较每个质因数在m和n!中的出现次数,从而找到最小的比例作为答案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值