题目:http://acm.nyist.net/JudgeOnline/problem.php?pid=640
求x+x^1+x^2+....x^n %c
当n为基数时;
这个式子 sum(x,n)= sum(x,n/2) * pow(x,n/2+1) +x
sum = (sum + x )%c
n为偶数时
sum(x,n) = sum(x,n/2) * pow(x,n/2) +1
然后使用快速幂,乘得出结果(其实我yy了一下的,一开始没有想到。。。。。。。。)
1 #include <stdio.h> 2 3 long long chenfa(long long a,long long b,long long c)//a*b%c 4 { 5 long long tmp = 0; 6 a %= c; 7 b %= c; 8 while(a) 9 { 10 if(a&1) 11 tmp = (tmp+b)%c; 12 a >>=1; 13 b <<=1; 14 b %= c; 15 } 16 return tmp; 17 } 18 19 long long pow1(long long a,long long b,long long c)//a^b%c 20 { 21 long long tmp = 1; 22 while(b) 23 { 24 if(b&1) 25 tmp = chenfa(a,tmp,c); 26 27 b >>= 1; 28 a = chenfa(a,a,c); 29 } 30 return tmp; 31 } 32 33 long long sum(long long a,long long b,long long c)//a +a^1 + a^2...+a^b %c 34 { 35 long long tmp = 0; 36 if(b == 1) 37 { 38 tmp = a%c; 39 } 40 else 41 { 42 if(b&1) 43 { 44 tmp = chenfa(sum(a,b/2,c),pow1(a,b/2+1L,c)+a,c); 45 tmp = (tmp +a )%c; 46 } 47 else 48 { 49 tmp = chenfa(sum(a,b/2,c),pow1(a,b/2,c)+1L,c); 50 } 51 52 return tmp; 53 } 54 } 55 int main() 56 { 57 long long a,b,c; 58 while(scanf("%lld%lld%lld",&a,&b,&c) != EOF) 59 { 60 printf("%lld\n",sum(a,b,c)); 61 } 62 return 0; 63 }