基准时间限制:1 秒 空间限制:131072 KB 分值: 20
难度:3级算法题
求:3^0 + 3^1 +...+ 3^(N) mod 1000000007
Input
输入一个数N(0 <= N <= 10^9)
Output
输出:计算结果
Input示例
3
Output示例
40
先用等比数列求和公式,ans = (3^(n+1) - 1)/ 2
然后用费马小定理对2求逆元,跑两次快速幂就行了。
代码如下:
#include <stdio.h>
#include <cstring>
#include <algorithm>
using namespace std;
#define CLR(a,b) memset(a,b,sizeof(a))
#define INF 0x3f3f3f3f
#define LL long long
const LL mod = 1000000007;
LL quick_mod(LL a,LL n)
{
LL ans = 1;
while (n)
{
if (n & 1)
ans = ans * a % mod;
a = a * a % mod;
n >>= 1;
}
return ans;
}
int main()
{
LL n;
scanf ("%lld",&n);
LL ans = quick_mod(3,n+1);
ans--;
LL inv = quick_mod(2,mod-2);
ans = ans * inv % mod;
printf ("%lld\n",ans);
return 0;
}