1013 3的幂的和(乘法逆元,快速幂)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_43540515/article/details/102748756

求:3^0 + 3^1 +…+ 3^(N) mod 1000000007
输入
输入一个数N(0 <= N <= 10^9)
输出
输出:计算结果
输入样例
3
输出样例
40
先用等比数列求和公式,ans = (3^(n+1) - 1)/ 2
然后用费马小定理对2求逆元,跑两次快速幂就行了。

乘法逆元

#include<bits/stdc++.h>
using namespace std;
#define ll long long
const ll mod=1000000007;
ll n;
ll quickpower(ll a,ll b)
{
 ll c=1;
 while(b)
 {
 	if(b%2) c=(c*a)%mod;
 	a=(a*a)%mod;
 	b/=2;
 }
 return c;
}
int main()
{
    ios::sync_with_stdio(false);	
    cin>>n;
    ll ans=quickpower(3,n+1)-1;
    ll inv=quickpower(2,mod-2);
	ans=ans*inv%mod;
    cout<<ans;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43540515/article/details/102748756