【转】等比数列二分求和
今天我们学习如何有效地求表达式的值。对于这个问题,用二分解决比较好。
(1)当时,
(2)当时,那么有
(3)当时,那么有
代码:
#include <iostream> #include <string.h> #include <stdio.h> using namespace std; const int M = 1000000007; typedef long long LL; LL power(LL a,LL b) { LL ans = 1; a %= M; while(b) { if(b & 1) { ans = ans * a % M; b--; } b >>= 1; a = a * a % M; } return ans; } LL sum(LL a,LL n) { if(n == 1) return a; LL t = sum(a,n/2); if(n & 1) { LL cur = power(a,n/2+1); t = (t + t * cur % M) % M; t = (t + cur) % M; } else { LL cur = power(a,n/2); t = (t + t * cur % M) % M; } return t; } int main() { LL a,n; while(cin>>a>>n) cout<<sum(a,n)<<endl; return 0; }