Rapid multiplication, rapid power, rapid decimal power, fast power matrix

Quick Take:

long long quick(long long  a,long long  b,long long c)
{
 long long ans=0;
 while(b)
  {
    if(b&1) ans=(ans+a)%c;
    b>>=1;
    a=(a+a)%c;
  }
  return ans;
}

 

Fast power:

long long B_quick(long long  a,long long  b,long long c)
{
 int ans=1;     
 a=a%c;     
 while(b)  
  {  
    if(b&1) ans=(ans*a)%c; 
    b>>=1;    
    a=(a*a)%c;   
  }  
 return ans;  
}

 

Fast Matrix Mi:

Fast power matrix and rapid power the same, but the numbers into a matrix.

const int N=10;
const long long mod=1e9;
void quick(long long ans[N][N],long long B[N][N],long long  n)
{
  for(int i=0;i<N;i++) ans[i][i]=1;
  while(n)
   {
      if(n&1) mul(ans,B,mod);
      mul(B,B,mod);
      n>>=1;
   }
}
void mul(long long C[N][N],long long D[N][N],long long mod)
{
  long long sum[N][N]={0};
  int i,j,k;
  for(i=0;i<N;i++)
   for(j=0;j<N;j++)
      for(k=0;k<N;k++)
        sum[i][j]=(sum[i][j]+C[i][k]*D[k][j]%mod);
  for(i=0;i<N;i++)
   for(j=0;j<N;j++)
    C[i][j]=sum[i][j]; 
}

 

Quick decimal power:

The binary nature of the fast power, of course, can also use decimal quick power. When the index is very large, the need for rapid power transition by decimal data processing, re-use binary power quickly solved.

const long long mod=1e9;
long long D_quick(long long a,string b,long long mod)
{
  long long sum=a,ans=1;
  for(int i=b.size()-1;i>=0;i--)
   {
     ans=ans*B_quick(sum,b[i]-'0')%mod;
     sum=B_quick(sum,10);
   }
  return ans;
}

 

Guess you like

Origin www.cnblogs.com/VividBinGo/p/11291850.html