快速幂模板
来源:http://www.cppblog.com/acronix/archive/2010/08/23/124470.aspx?opt=admin
下面是 m^n % k 的快速幂:
1 // m^n % k 2 int quickpow(int m,int n,int k) 3 { 4 int b = 1; 5 while (n > 0) 6 { 7 if (n & 1) 8 b = (b*m)%k; 9 n = n >> 1 ; 10 m = (m*m)%k; 11 } 12 return b; 13 }
快速幂原理讲解:http://www.cnblogs.com/CXCXCXC/p/4641812.html
下面是矩阵快速幂:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //HOJ 3493 2 /*===================================*/ 3 || 快速幂(quickpow)模板 4 || P 为等比,I 为单位矩阵 5 || MAX 要初始化!!!! 6 || 7 /*===================================*/ 8 /*****************************************************/ 9 #include <cstdio> 10 const int MAX = 3; 11 12 typedef struct{ 13 int m[MAX][MAX]; 14 } Matrix; 15 16 Matrix P = {5,-7,4, 17 1,0,0, 18 0,1,0, 19 }; 20 21 Matrix I = {1,0,0, 22 0,1,0, 23 0,0,1, 24 }; 25 26 Matrix matrixmul(Matrix a,Matrix b) //矩阵乘法 27 { 28 int i,j,k; 29 Matrix c; 30 for (i = 0 ; i < MAX; i++) 31 for (j = 0; j < MAX;j++) 32 { 33 c.m[i][j] = 0; 34 for (k = 0; k < MAX; k++) 35 c.m[i][j] += (a.m[i][k] * b.m[k][j])%9997; 36 c.m[i][j] %= 9997; 37 } 38 return c; 39 } 40 41 Matrix quickpow(long long n) 42 { 43 Matrix m = P, b = I; 44 while (n >= 1) 45 { 46 if (n & 1) 47 b = matrixmul(b,m); 48 n = n >> 1; 49 m = matrixmul(m,m); 50 } 51 return b; 52 } 53 /*************************************/ 54 55 int main() 56 { 57 Matrix re; 58 int f[3] = {2,6,19}; 59 long long n; 60 while (scanf("%I64d",&n) && n != 0) 61 { 62 if (n == 1) 63 printf("1\n"); 64 else if (n <= 4) 65 printf("%d\n",f[n-2]); 66 else { 67 re = quickpow(n - 4); 68 printf("%d\n",(((re.m[0][0]*f[2]) 69 + (re.m[0][1]*f[1]) + (re.m[0][2]*f[0])) %9997 + 9997) % 9997); 70 } 71 } 72 return 0; 73 }
OJ题目:codevs 1497 取余运算
题目描述 Description
输入b,p,k的值,编程计算bp mod k的值。其中的b,p,k*k为长整型数(2^31范围内)。
输入描述 Input Description
b p k
输出描述 Output Description
输出b^p mod k=?
=左右没有空格
样例输入 Sample Input
2 10 9
样例输出 Sample Output
2^10 mod 9=7
超时的代码:
1 #include <iostream> 2 using namespace std; 3 long long i,n=0,m=0,l=0,ans=0; 4 int main(void) 5 { 6 ans=1; 7 cin>>n>>m>>l; 8 for (i=1;i<=m;i++) 9 ans=(ans*n)%l; 10 cout<<n<<'^'<<m<<" mod "<<l<<'='<<ans; 11 return 0; 12 }
AC代码:(注意类型要用long long)
1 #include <stdio.h> 2 long long quickpow(long long m,long long n,long long k); 3 int main(int argc, char *argv[]) 4 { 5 long long b,p,k; 6 scanf("%lld%lld%lld",&b,&p,&k); 7 printf("%lld^%lld mod %lld=%lld",b,p,k,quickpow(b,p,k)); 8 return 0; 9 } 10 // m^n % k 11 long long quickpow(long long m,long long n,long long k) 12 { 13 long long ans = 1; 14 while (n > 0) 15 { 16 if (n & 1) 17 ans = (ans*m)%k; 18 n = n >> 1 ; 19 m = (m*m)%k; 20 } 21 return ans; 22 }