文章转自:http://blog.csdn.net/a15110103117
Sumdiv
Description
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). Source |
题意:
给出a,b(0<=a,b<=50000000),求出q为a,n为b的等比数列和。例如:1+2+2^2+2^3+......
思路:
之前我还以为直接上公式再取余就完了,之后就惨不忍睹。
真正的做法是:
1.先把a分解成小数,比如36^100=2^200*3^200(至于为什么一定要分解就不清楚了,我直接递归求和是WA)
2.递归求和
n为奇数时:(1+p+p^2...p^(n/2))*(1+p^(n/2+1))
n为偶数时:(1+p+p^2...p^(n/2-1))*(1+p^(n/2+1))+p^(n/2)
这个式子可以在纸上推出来,黑色部分做递归就可以了,当n=0时就是递归的终点。
对于乘方需要快速幂,这里不给予叙述,详情请咨询百度。
#include <iostream>
#include <cstdlib>
#include <cstdio>
using namespace std;
long long sort_pow(int a, int b) //二分求幂
{
long long r = 1, base = a;
while( b )
{
if( b%2==1 )
r = ( r*base )%9901;
base = ( base*base )%9901;
b /= 2;
}
return r;
}
long long multi(int a, long long b) //递归求和
{
if( b==0 )
return 1;
else if( b%2==1 )
return multi(a,b/2)*(1+sort_pow(a,b/2+1))%9901;
else
return (multi(a,b/2-1)*(1+sort_pow(a,b/2+1))%9901 + sort_pow(a,b/2))%9901;
}
long long dell( int a, int b )
{
long long mul = 1;
int cnt;
for( int i = 2; i*i <= a;i++ ) //遍历到 sqrt(a) 就好,类似原始的素数求法
{
cnt = 0;
while( a%i==0 ) //因式分解
{
a /= i;
cnt++;
}
mul = mul * multi(i,b*cnt)%9901;
}
if( a!=1 )
{
mul = mul*multi(a,b)%9901;
}
return mul;
}
int main()
{
int a, b;
cin>>a>>b;
cout<<dell(a,b)<<endl;
return 0;
}