51nod 1513-3的幂的和(费马小定理+快速幂)
题目:
求:3^0 + 3^1 +...+ 3^(N) mod 1000000007
Input
输入一个数N(0 <= N <= 10^9)
Output
输出:计算结果
Sample Input
3
Sample Output
40
思路:根据等比数列的前N项和公式可得到原式等于((3的n次方+1)/2)%1e9+7,用快速幂求出3的n次方,再由费马小定理求出2的逆元(观察也可知道,2对与1000000007的逆元为500000004)。
代码:
#include <iostream>
using namespace std;
typedef long long ll;
const ll MOD=1e9+7;
ll quickpow(ll a,ll b)
{
int ans=1;
a=a%MOD;
while(b)
{
if(b & 1) ans=ans*a%MOD;
b>>=1;
a=a*a%MOD;
}
return ans;
}
int main()
{
int n;
ll m,q;
cin>>n;
m=quickpow(3,n+1)-1;
q=quickpow(2,MOD-2);
cout<<m*q%MOD<<endl;
return 0;
}