zoukankan      html  css  js  c++  java
  • 快速幂

    快速幂的原理:a^b=(a*a)^b/2(当b为偶数)

                        a^b=a*(a*a)^((b-1)/2)(当b为奇数)

    a^b%mod=((a*a)%mod)^b/2%mod;

    基础的快速幂模板代码:

    (递归写的)

     1 #include<iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 using namespace std;
     5 int mod;
     6 int mat(int a,int b)///a^b,结果对mod取膜,b的值很大的时候
     7 {
     8     int c=1;
     9     if(b==1) return a%mod; ///当b为1时,只剩下最后一个a
    10     else if(b&1)  ///b为奇数
    11         return mat(a,b-1)*a%mod; ///把单独的a拿出来
    12     else ///b为偶数
    13         return mat(a*a,b/2)%mod; ///直接相乘,系数除以2
    14 }
    15 int main()
    16 {
    17     int a,b;
    18     while(~scanf("%d%d%d",&a,&b,&mod))
    19         cout<<mat(a,b)<<endl;
    20     return 0;
    21 }

    矩阵快速模模板代码:

     1 struct mat
     2 {
     3     int m[10][10];
     4 };
     5 int mod;
     6 
     7 mat mul(mat a,mat b)
     8 {
     9     mat c;
    10     int i,j,k;
    11     memset(c.m,0,sizeof(c.m));
    12     for(i=0; i<10; i++)
    13         for(j=0; j<10; j++)
    14         {
    15             for(k=0; k<10; k++)
    16             {
    17                 c.m[i][j]+=(a.m[i][k]*b.m[k][j])%mod;
    18             }
    19             c.m[i][j]%=mod;
    20         }
    21     return c;
    22 }
    23 
    24 mat product(mat a,int k)
    25 {
    26     if(k==1) return a;
    27     else if(k&1)
    28         return mul(product(a,k-1),a);
    29     else
    30         return product(mul(a,a),k/2);
    31 }
  • 相关阅读:
    [mysql] information_schema数据库表
    Linux 进程操作_12
    Linux 标准输入输出_11
    apache2
    poj 3083 Children of the Candy Corn 夜
    poj 2151 Check the difficulty of problems 夜
    poj 3274 Gold Balanced Lineup 夜
    poj 3414 Pots 夜
    poj Finicky Grazers 3184 夜
    poj 3253 Fence Repair 夜
  • 原文地址:https://www.cnblogs.com/pshw/p/5542696.html
Copyright © 2011-2022 走看看