Wannafly挑战赛25 A 因子(n!中p的个数)

题意:链接:https://www.nowcoder.com/acm/contest/197/A
来源:牛客网

令 X = n!, 给定一大于1的正整数p 求一个k使得 p ^k | X 并且 p ^(k + 1) 不是X的因子。

思路:转化成求X含多少p,p可以分解成2^a*3^b*……,就可以转化成求X里2的个数,2的个数……,比如样例2的n=10000 p=12,那么p=2^2*3,然后看n!有多少2和3,再“分配”给p,我们知道,n的阶乘里2的个数为 n/2+n/4+n/8+……,3的个数为n/3+n/9+……,然后p需要2个2,1个3,所以让n!中2的个数除以2就是能组成p的2的个数,3也一样,最后取p的因子里面配的最少的个数,因为其他就算再多也需要这个最少的因子才能配成p。

#include<bits/stdc++.h>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
const int maxn=200005;
const int mod=1e9+7;
const double eps=1e-8;
const double PI = acos(-1.0);
#define lowbit(x) (x&(-x))
ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);}
ll qpow(ll a,ll b){ll t=1;while(b){if(b%2){t=(t*a)%mod;b--;}a=(a*a)%mod;b/=2;}return t;}
int main()
{
    std::ios::sync_with_stdio(false);
    ll n,p,ans=1e18;
    cin>>n>>p;
    for(int i=2;i<=p;i++)
    {
        ll sum=0,t=0,nn=n;
        while(p%i==0)
        {
            p/=i;
            t++;
        }
        while(nn)
        {
            nn/=i;
            sum+=nn;
        }
        if(t)
        ans=min(sum/t,ans);
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Dilly__dally/article/details/83152272