快速幂取模
用法:用于求解 a 的 b 次方,而b是一个非常大的数,用O(n)的复杂度会超时。那么就需要这个算法,注意它不但可以对数求次幂,而且可用于矩阵快速幂。
假如求 x ^ n 次方
我们可以把 n 表示为 2^k1 + 2^k2 + 2^k3....,可以证明所有数都可以用前式来表示。(其实就是二进制表示数的原理,k1,k2……就是二进制的每一位)
那么 x^n = x^2^k1 * x^2^k2 * x^2^k3......
那么就可以利用二进制来加快计算速度了。
假如 x^22 , 22转化为二进制为 10110, 即 x^22 = x^16 * x^4 * x^2;
那么是不是可以在O(logn)的复杂度求解。
代码:
typedef long long LL; LL fun(LL x,LL n,) { LL res=1; while (n>0) { if (n & 1) res=(res*x)%Max; x=(x*x)%Max; n >>= 1; } return res; }
那么假如让你求一个矩阵的很大的次方幂呢,当然我们同样可以求解。
比如我们都知道斐波那契数列可以用矩阵来求
当求第非常大的一个斐波那契数的后几位时我们可以用上面方法求解了。
方法和上面的方法一模一样,只是把数 x 变成了一个矩阵。
注意代码中矩阵的存法,很好用,题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=148
#include <cstdio> #include <iostream> #include <vector> using namespace std; typedef vector< int > vec; typedef vector<vec> mat; typedef long long LL; const int N = 10000; mat mul(mat a,mat b) { mat c(a.size(),vec(b[0].size())); for ( int i=0;i<a.size();i++) { for ( int k=0;k<b.size();k++) { for ( int j=0;j<b[0].size();j++) c[i][j] = ( c[i][j] + a[i][k] * b[k][j] ) % N; } } return c; } mat solve_pow(mat a,int n) { mat b(a.size(),vec(a.size())); for ( int i=0;i<a.size();i++) b[i][i]=1; while (n>0) { if (n & 1) b=mul(b,a); a=mul(a,a); n >>= 1; } return b; } LL n; void solve() { mat a(2,vec(2)); while (~scanf( "%d" ,&n) && n!=-1) { a[0][0]=1,a[0][1]=1; a[1][0]=1,a[1][1]=0; a=solve_pow(a,n); printf("%d\n" ,a[1][0]); } } int main() { solve(); return 0; }
原文:http://blog.csdn.net/y990041769/article/details/22311889