快速幂
如计算 a^b^ ,代码如下:
快速幂代码
快速幂取模:
int multi(int a,int b, int mod)
{
int ans = 1,base = a;
while(b!=0)
{
if(b&1)
ans = ans * base % mod;
base = base * base % mod;
b>>=1;
}
return ans % mod; //最后不要忘记还要取模
}
快速幂:
int multi(int a,int b, int mod)
{
int ans = 1,base = a;
while(b!=0)
{
if(b&1)
ans = ans * base ;
base = base * base;
b>>=1;
}
return ans;
}
矩阵快速幂
它可以快速求出斐波那契数列,这里以一个题为例,Fibonacci POJ - 3070
AC代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
const int MOD = 10000;
struct matrix { //矩阵
int m[2][2];
}ans;
matrix base = {1, 1, 1, 0};
matrix multi(matrix a, matrix b) { //矩阵相乘,返回一个矩阵
matrix tmp;
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
tmp.m[i][j] = 0;
for(int k = 0; k < 2; k++)
tmp.m[i][j] = (tmp.m[i][j] + a.m[i][k] * b.m[k][j]) % MOD;
}
}
return tmp;
}
int matrix_pow(matrix a, int n) { //矩阵快速幂,矩阵a的n次幂
ans.m[0][0] = ans.m[1][1] = 1; //初始化为单位矩阵
ans.m[0][1] = ans.m[1][0] = 0;
while(n) {
if(n & 1) ans = multi(ans, a);
a = multi(a, a);
n >>= 1;
}
return ans.m[0][1];
}
int main() {
int n;
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
while(scanf("%d", &n), n != -1) {
printf("%d
", matrix_pow(base, n));
}
return 0;
}
参考博客:https://blog.csdn.net/alps1992/article/details/42131581
https://blog.csdn.net/u014355480/article/details/44659245