快速幂模板

快速幂算法模板

求 m^n%p,时间复杂度 O(logn)。
 
int qmi(int a, int b, int p)
{
    int res = 1;
    while (b)
    {
        if (b&1) res = (res * a) % p;
        a = (a * a) % p;
        b = b>> 1;
    }
    return res;
}

  

 

64位整数乘法模板

求 m*n%p,时间复杂度 O(logn)。
int qji(int a, int b, int p)
{
    int res = 0;
    while (b)
    {
        if (b&1) res = (res + a) % p;
        a = (a * 2) % p;
        b = b>> 1;
    }
    return res;
}

  实例:

#include<bits/stdc++.h>
using namespace std;
long long a,b,p;
int main()
{
  ios::sync_with_stdio(0);
  cin>>a>>b>>p;
  long long res=0;
  while(b)
  {
    if(b&1)res=(res+a)%p;//必须先加起来再取余 括号不能去
    a=a*2%p;
    b=b>>1;
  }
  cout<<res%p<<"
";
  return 0;
}

  

原文地址:https://www.cnblogs.com/52dxer/p/10353029.html