求:3^0 + 3^1 +...+ 3^(N) mod 1000000007
Input
输入一个数N(0 <= N <= 10^9)
Output
输出:计算结果
Sample Input
3
Sample Output
40
运用等比数列公式减小复杂度和费马小定理求逆元
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef long long ll;
const long long p=1e9+7;
LL pow_mod(LL a, LL b){//a的b次方
if(b == 0) return 1;
LL ret = pow_mod(a, b/2);
ret = ret * ret % p;
if(b % 2 == 1) ret = ret * a % p;
return ret;
}
ll qpow(ll a,ll b,ll p)
{
ll tmp = 1;
while(b)
{
if(1&b) tmp = (tmp*a)%p;
a = (a*a)%p;
b>>=1;
}
return tmp;
}
ll inv(ll a,ll p) //费马小定理求逆元
{
return qpow(a,p-2,p);
}
int main()
{
LL n,s,x,last;
x=3;
cin>>n;
s=pow_mod(x,n+1)-1;
last=s*inv(2,p);
cout<<last%p<<endl;
}