poj 1845 (逆元 + 约数和)

题意:

求A^B的所有约数(即因子)之和,并对其取模 9901再输出。


思路:

 A可以表示为A=(p1^k1)*(p2^k2)*(p3^k3)*....*(pn^kn)   其中pi均为素数

那么A的所有因子之和可以表示成

 S = (1+p1+p1^2+p1^3+...p1^k1) * (1+p2+p2^2+p2^3+….p2^k2) * (1+p3+ p3^3+…+ p3^k3) * .... * (1+pn+pn^2+pn^3+...pn^kn)

然后可以转化成等比公式,在求除法同余的时候求逆元

对于 a/b mod m可以转化成 (a mod bm)/m         /*参考ACdreamers



#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
typedef long double ld;
const ld eps=1e-10;
const int inf = 0x3f3f3f;
const int maxn = 1e6+10;
bool check[maxn];
int prime[maxn];

ll tot;



void get_prime()
{
    tot = 0;
    memset(check,false,sizeof(check));
    check[1] = true;
    for(int i = 2; i<= maxn; i++)
    {
        if(!check[i])
        {
            prime[tot++] = i;
            for(int j = i+i; j <= maxn; j+=i)
                check[j] = true;
        }
    }
}

ll multi(ll a,ll b,ll mod)
{
    ll ans = 0;
    a%=mod;
    while(b)
    {
        if(b & 1)
        {
            ans = (ans+a) % mod;
            b -- ;
        }
        a = (a+a) % mod;
        b >>= 1;
    }
    return ans;
}

ll pow_mod(ll a,ll n,ll p)
{
    ll ans = 1;
    a %= p;
    while(n)
    {
        if(n & 1)
        {
            ans = multi(ans,a,p);
            n--;
        }

        a = multi(a,a,p);
        n >>= 1;
    }
    return ans;
}


ll sum(ll x,ll b)
{
    ll t = 1;
    ll tnum = 0;
    ll tmp = x;
    for(int i = 0; i < tot; i++)
    {
        if(tmp % prime[i] == 0)
        {
            tnum = 0;
            while(tmp % prime[i] == 0)
            {
                tmp /= prime[i];
                tnum ++;
            }
            ll M = (prime[i]-1)*9901;
            t *= (pow_mod(prime[i],tnum*b+1,M)-1+M)/(prime[i]-1);
            t %= 9901;
        }
    }
    if(tmp > 1)
    {
        ll M = (tmp-1)*9901;
        t *= (pow_mod(tmp,tnum*b+1,M)-1+M)/(tmp-1);
        t %= 9901;
    }
    return t%9901;
}

int main()
{
    ll a,b;
    get_prime();
    while(scanf("%I64d%I64d",&a,&b) != EOF)
    {
        printf("%I64d
",sum(a,b)%9901);
    }
    return 0;
}

  


原文地址:https://www.cnblogs.com/Przz/p/5409651.html