快速幂模m算法

给你三个数,a,b,m

求a^b%m的值。

如果b过大,用普通的快速幂会超时。

所以将b=2^0*b0+2^1*b+b1......

然后,你们利用初中的知识就知道怎么做了。

继续,上代码。

#include <iostream>
#include <fstream>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
using namespace std;

long long quick_mod(long long a,long long b,long long m){
long long ans=1;
while(b){
  if(b&1)ans=(ans*a)%m;    
  b/=2;
  a=a*a%m;
 }    
return ans;    
}


int main(int argc, char** argv) {
long long int a,b,m;
cin>>a>>b>>m;
cout<<quick_mod(a,b,m);
return 0;
}
View Code
原文地址:https://www.cnblogs.com/Ateisti/p/5618537.html