多校15场Harry Potter and the Hide Story(合数分解)

出题者愿意可能是要用随机算法,不过还是被朴素的素数表给水掉了。。。

题意:给出n,k(n是ll范围 , k是10^14)求最大的x使k^x整除n!

当k不等于1时,先将k分解成素数乘积形式,记录指数,找出n!中相对的素数的指数与k分解后指数之比的最小值即可

 

#include <cstdio>
#include <cstring>
#define abs(a) (a)>(0)?(a):(-(a))
#define  min(a,b) (a>b?b:a)

typedef long long ll;

const int PRIMERANGE = 10000000;
int prime[PRIMERANGE + 1];//prime[0] is the counter
int getPrime()
{
    memset (prime, 0, sizeof (int) * (PRIMERANGE + 1));
    for (int i = 2 ; i <= PRIMERANGE ; i++)
    {
        if (!prime[i]) prime[++prime[0]] = i;
        for (int j = 1; j <= prime[0] && prime[j] <= PRIMERANGE / i; j++)
        {
            prime[prime[j]*i] = 1;
            if (i % prime[j] == 0) break;
        }
    }
    return prime[0];
}

long long factor[100][2];
int facCnt;

int getFactors(long long x)
{
    facCnt = 0;
    long long tmp = x;
    for(int i = 1; prime[i] <= tmp / prime[i]; i++)
    {
        factor[facCnt][1] = 0;
        if(tmp % prime[i] == 0)
        {
            factor[facCnt][0] = prime[i];
            while(tmp % prime[i] == 0)
            factor[facCnt][1]++, tmp /= prime[i];
            facCnt++;
        }
    }
    if(tmp != 1)
        factor[facCnt][0] = tmp, factor[facCnt++][1] = 1;
    return facCnt;
}

ll n,k;
int main ()
{
    getPrime();
    int cas;
    scanf("%d",&cas);
    for (int I=1 ; I<=cas ; ++I)
    {
        scanf("%I64d%I64d",&n,&k);
        if(k==1){printf("Case %d: inf\n",I);continue;}
        ll nn;
        ll ans;
        int fcnt=getFactors(k);
        for (int i=0 ; i<fcnt ; ++i)
        {
            ll cnt=0;
            for (nn=n ; nn ; nn/=factor[i][0])
            {
                cnt+=nn/factor[i][0];
            }
            ll tmp=cnt/factor[i][1];
            if(i==0)ans=tmp;
            else 
            ans=min (tmp , ans);
        }
        printf("Case %d: %I64d\n",I,ans);
    }
    return 0;
}


 

你可能感兴趣的:(多校15场Harry Potter and the Hide Story(合数分解))