3的幂的和 (快速幂+逆元+同余定理)

求:3^0 + 3^1 +...+ 3^(N) mod 1000000007

Input

输入一个数N(0 <= N <= 10^9)

Output

输出:计算结果

Sample Input

3

Sample Output

40

先分析一下复杂度,光是跑完a就要1e+9,而计算机1s大概pao1e+8那个数量级,显然不能直接用for暴力。考虑到她是等比数列,我们可以用前n项和公式,再对公式用同余定理+逆元+快速幂求解。

AC代码如下:

#include<stdio.h>
#include<algorithm>
#include<math.h>
#include<iostream>
#include<map>
const int mod=1e9+7;
#include<vector>
#include<set>
#include<string>
#include<string.h>
using namespace std;
typedef long long ll;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
	if(b==0)
	{
		y=0;
		x=1;
		return a;
	}
	ll r=exgcd(b,a%b,x,y);
	ll t=y;
	y=x-(a/b)*y;
	x=t;
	return r;
}
ll iva(ll a)
{
	ll x,y;
	exgcd(a,mod,x,y);
	return (x+mod)%mod;
}
ll fast_mod(ll a,ll n)
{
	ll res=1;
	while(n)
	{
		if(n&1)	res=(res*a)%mod;
		a=a*a%mod;
		n>>=1;
	}
	return res;
}
int main()
{
	ll x,y,m,n,sum=0;
	int i;
	scanf("%d",&n);
	y=fast_mod(3,n+1);
	x=iva(2);
	printf("%lld\n",((y-1)%mod*(x%mod))%mod);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/doubleguy/article/details/81192723