51nod 1013 3的冪的和(除法取模+快速冪)
阿新 • • 發佈:2018-12-20
基準時間限制:1 秒 空間限制:131072 KB 分值: 20 難度:3級演算法題
收藏
關注
取消關注
求:3^0 + 3^1 +...+ 3^(N) mod 1000000007
Input
輸入一個數N(0 <= N <= 10^9)
Output
輸出:計算結果
Input示例
3
Output示例
40
分析:等比數列前(n+1)項和,公比為3,首項為1.所以ans=( 3^(n+1)-1 ) / 2 % 1000000007.
3^(n+1)用快速冪很好解決,而除法取模只需將除法變乘法即可,也就是用被除數去乘以除數的乘法逆元.
求乘法逆元用費馬小定理:當模為素數,a的逆元為pow_mod(a,mod-2).
程式碼:
//(3^(n+1)-1)/2%mod; #include <iostream> using namespace std; typedef long long ll; const int mod=1e9+7; ll ans; ll pow_mod(ll a,ll i) { ll ans=1; while(i) { if(i&1) ans=(ans*a)%mod; a=(a*a)%mod; i>>=1; } return ans; } int main() { ll n; ios::sync_with_stdio(false); while(cin>>n) { ans=pow_mod(3,n+1)-1; ans=(ans*pow_mod(2,mod-2))%mod; cout<<ans<<endl; } return 0; }