首项为1次项的,前面的博客中已经有过讲解:http://blog.youkuaiyun.com/rain722/article/details/71034438
附上代码:
#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;
}
首先注明n为不包含0次项的项数,比如a^0, a^1, a^2, a^3, a^4这个等比数列的项数需要传入的参数为n = 4
S(n)表示包括0次项即1但不计入项数内的前n项和,比如S(4) = a^0 + a^1 + a^2 + a^3 + a^4
n为奇数(不包括0次项即1的项为奇数)
S(n) = (1+a^(n/2 + 1)) * S(n/2)
n为偶数(不包括1的项)
S(n) = (1+a^(n/2)) * S(n/2 - 1) + a^n
代码:需要注意的是传入的参数n为不包括0次项的项数
#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 == 0) return 1;
LL t = sum(a,(n-1)/2);
if(n & 1)
{
LL cur = power(a,n/2+1);
t = (t + t * cur % M) % M;
}
else
{
LL cur = power(a,n/2);
t = (t + t * cur % M) % M;
t = (t + power(a,n)) % M;
}
return t;
}
int main()
{
LL a,n;
while(cin>>a>>n)
cout<<sum(a,n)<<endl;
return 0;
}