poj 1845 Sumdiv(同余模公式)

来源:互联网 发布:数据库实例 schema关系 编辑:程序博客网 时间:2024/05/07 01:53

http://poj.org/problem?id=1845

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 = p1^a1*p2^a2.....*pn^an,

则A^B=(p1^a1*p2^a2.....*pn^an)^B = p1^(a1*B)*p2^(a2*B).....*pn^(an*B)

所有正约数和S = (1+p1+p1^2+...p1^(a1*B)) + (1+p2+p2^2+...p2^(a2*B)) + ... (1+pn+pn^2+...pn^(an*B))

可见ss = (1+p+p^2+...p^n)是等比数列的和,递归二分求该等比数列的和

当n为奇数时,一共有偶数项

ss = (1+p^(n/2+1)) + p* (1+p^(n/2+1)) + ... p^(n/2) *  (1+p^(n/2+1));

    =  (1+p+p^2+...p^(n/2)) * (1+p^(n/2+1))

当n为偶数时,一共有奇数项

ss = (1+p^(n/2)+1) * p * (1+p^(n/2)+1) * ... p^(n/2-1) * (1+p^(n/2)+1) + p^(n/2);

    = (1+p+p^2+...p^(n/2-1)) * (1+p^(n/2+1)) + (p^(n/2))

同余模公式:

(a+b)%mod = (a%mod+b%mod)%mod; 

(a*b)%mod = (a%mod*b%mod)%mod; 

根据同余模公式即可求的结果

#include <iostream>#include <queue>#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <cstdlib>#include <limits>#include <stack>#include <vector>#include <map>using namespace std;#define N 1002000#define INF 0xfffffff#define PI acos (-1.0)#define EPS 1e-8#define met(a, b) memset (a, b, sizeof (a))typedef long long LL;LL a;int isprim[N] = {1, 1}, prim[N], cnt = 0, t, b;struct node{    LL p, a;} stu[N];void Init (){///素数打表    for (int i=2; i<1001000; i++)    {        if (!isprim[i])        {            prim[cnt++] = i;            for (int j=i+i; j<1001000; j+=i)                isprim[j] = 1;        }    }}void Fenjie (){///唯一分解定理    t = 0;    for (int i=0; i<cnt; i++)    {        int k = 0;        if (a%prim[i]==0)        {            while (a%prim[i]==0)            {                k++;                a /= prim[i];            }            stu[t].a = k;            stu[t++].p = prim[i]%9901;        }        if (a==1) break;    }    if (a!=1)        stu[t].p = a%9901, stu[t++].a = 1;}LL Quick_Pow (int m, int n){///快速幂    LL temp = 1;    while (n)    {        if (n&1)            temp = temp * m % 9901;        n >>= 1;        m = m * m % 9901;    }    return temp;}LL sum (int p, LL n){///等比数列递归二分求和    if (n==0) return 1;    if (n%2) return (sum (p, n/2) * (1+Quick_Pow(p, n/2+1)))%9901;    else return (sum (p, n/2-1) * (1+Quick_Pow(p, n/2+1)) + Quick_Pow(p, n/2))%9901;}int main (){    Init();    while (scanf ("%I64d %d", &a, &b) != EOF)    {        met (stu, 0);        if (a==1 || !a)        {            puts ("1");            continue;        }                Fenjie();        LL ans = 1;        for (int i=0; i<t; i++)            ans = (ans * sum(stu[i].p, stu[i].a*b)%9901) % 9901;        printf ("%I64d\n", ans%9901);    }    return 0;}

1 0
原创粉丝点击