前言
快速幂专题其实很久以前就刷完了,但是还是再写一篇博客巩固一下记忆。
序列的第K个数
我们知道,等差数列的第n项公式是Sn=a1+(n−1)×q,等比数列的第n项是Sn=a1(1−qn)/(1−q)。
根据题意,我们可以判断这个数列属于等差数列还是等比数列,如果是等比数列就用快速幂来求。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #include <bits/stdc++.h> using namespace std; const int mod=200907; typedef unsigned long long ll; ll qpow(ll a,ll b){ ll res=1; while(b){ if(b&1) res=(res*a)%mod; a=(a*a)%mod; b>>=1; } return res%mod; } int n; int main(){ cin>>n; while(n--){ ll a,b,c,k; cin>>a>>b>>c>>k; if(c-b==b-a){ cout<<(a+(k-1)*(c-b))%mod<<endl; } else cout<<a*qpow(b/a,k-1)%mod<<endl; } return 0; }
|
A的B次方
快速幂模板题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include <bits/stdc++.h> using namespace std; const int mod=200907; typedef long long ll; ll qpow(ll a,ll b,ll p){ ll res=1; while(b){ if(b&1) res=(res*a)%p; a=(a*a)%p; b>>=1; } return res%p; } int n; int main(){ ll a,b,m; cin>>a>>b>>m; cout<<qpow(a,b,m); return 0; }
|
转圈游戏
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <bits/stdc++.h> using namespace std; const int mod=200907; typedef long long ll; ll qpow(ll a,ll b,ll p){ ll res=1; while(b){ if(b&1) res=(res*a)%p; a=(a*a)%p; b>>=1; } return res%p; } int main(){ ll n,m,k,x; cin>>n>>m>>k>>x; cout<<(x+qpow(10,k,n)*m)%n; return 0; }
|
越狱
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| #include <bits/stdc++.h> using namespace std; const int mod=100003; typedef long long ll; ll qpow(ll a,ll b){ ll res=1; while(b){ if(b&1) res=(res*a)%mod; a=(a*a)%mod; b>>=1; } return res%mod; } int main(){ ll m,n; cin>>m>>n; cout<<(qpow(m,n)%mod-m*qpow(m-1,n-1)%mod+mod)%mod; }
|