天天看點

POJ-1845-Sumdiv (唯一分解定理、快速幂、費馬小定理)

原題連結:

Consider two natural numbers A and B. Let S be the sum of all natural divisors of A^B. Determine S modulo 9901 (the rest of the division of S by 9901).

Input

The only line contains the two natural numbers A and B, (0 <= A,B <= 50000000)separated by blanks.

Output

The only line of the output will contain S modulo 9901.

Sample Input

2 3

Sample Output

15

Hint

2^3 = 8.

The natural divisors of 8 are: 1,2,4,8. Their sum is 15.

15 modulo 9901 is 15 (that should be output).

題意:

輸入a和b,求a^b的因子之和。

題解:

利用唯一分解定理,将a标準分解,然後每一個素數的指數都擴大b倍,最後利用公式求和,等比數列求和時,分母可以通過費馬小定理求逆元,然後一同求餘。

附上AC代碼:

#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
const int mod=9901;
const int N=sqrt(5e7)+5;
int prime[N],cnt=0;
bool vis[N];
void el()//素數打表
{
    memset(vis,0,sizeof(vis));
    for(int i=2;i<=N;i++)
    {
        if(!vis[i])
        {
            prime[cnt++]=i;
            for(int j=i*2;j<=N;j+=i)
            {
                vis[j]=1;
            }
        }
    }
}
int quickpow(int a,int b)//快速幂
{
    int ans=1;
    while(b!=0)
    {
        if(b&1)
            ans=(ans*a)%mod;
        a=(a*a)%mod;
        b>>=1;
    }
    return ans;
}
int main()
{
    el();
    int a,b;
    scanf("%d%d",&a,&b);
    int sum=1;
    for(int i=0;i<cnt&&prime[i]<=a;i++)//唯一分解定理求出a的分解後各個素數的指數
    {
        if(a%prime[i]==0)
        {
            int e=0;
            while(a%prime[i]==0)
            {
                a/=prime[i];
                e++;
            }
            //利用快速幂計算出因子的和(等比數列求和)以及費馬小定理求出逆元
            int x=(((quickpow(prime[i],(b*e+1)))-1)*quickpow(prime[i]-1,mod-2))%mod;
            sum=(sum*x)%mod;//求和
        }
    }
    printf("%d\n",sum);
    return 0;
}

           

歡迎評論!