zoukankan      html  css  js  c++  java
  • 快速幂及快速幂求逆元

    1.快速幂

    代码:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <string.h>
     5 #include <math.h>
     6 #include <algorithm>
     7 #include <stack>
     8 #include <queue>
     9 #include <vector>
    10 #include <map>
    11 #include <set>
    12 #define ll long long
    13 const int N=1e6+10;
    14 const int mod=1e9;
    15 using namespace std;
    16 typedef pair<int,int>PII;
    17 
    18 int fpow(int a,int k,int p){
    19    int res=1;
    20     while(k){
    21       if(k&1) res=(ll)res*a%p;
    22       k>>=1;    //k=k>>1;
    23       a=(ll)a*a%p;
    24     }
    25     return res;
    26 }
    27 
    28 int main(){
    29  ios::sync_with_stdio(false);
    30  int n;
    31   cin>>n;
    32    while(n--){
    33     int a,k,p;
    34      cin>>a>>k>>p;
    35        
    36      printf("%d\n",fpow(a,k,p));
    37    }
    38   return 0;
    39 }

    2.快速幂求逆元

    代码:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <cmath>
     5 #include <algorithm>
     6 #include <stack>
     7 #include <queue>
     8 #include <vector>
     9 #include <map>
    10 #include <set>
    11 #include <unordered_set>
    12 #include <unordered_map>
    13 #define ll long long
    14 #define fi first
    15 #define se second
    16 #define pb push_back
    17 #define me memset
    18 const int N = 1e6 + 10;
    19 const int mod = 1e9 + 7;
    20 using namespace std;
    21 typedef pair<int,int> PII;
    22 typedef pair<long,long> PLL;
    23 
    24 
    25 int n;
    26 int a,p;
    27 
    28 int fpow(int a,int p,int m){
    29     int res=1;
    30     while(p){
    31         if(p&1) res=(ll)res*a%m;
    32         p>>=1;
    33         a=(ll)a*a%m;
    34     }
    35     return res;
    36 }
    37 
    38 int main() {
    39     ios::sync_with_stdio(false);
    40     cin>>n;
    41      while(n--){
    42          cin>>a>>p;
    43          if(a%p)
    44          printf("%d\n",fpow(a,p-2,p));
    45          else puts("impossible");
    46      }
    47 
    48     return 0;
    49 }
  • 相关阅读:
    2014 HDU多校弟九场I题 不会DP也能水出来的简单DP题
    POJ 2208 Pyramids 欧拉四面体
    BNU 4067 求圆并
    POJ 3675 Telescope 简单多边形和圆的面积交
    POJ 2451 Uyuw's Concert(半平面交nlgn)
    [置顶] 程序员期望月薪那些事儿
    一、转正的那些事儿
    鼓膜内陷(听别人说话还震动)
    程序员的职场潜意识Top10
    年过40岁的雷军致已逝去的青春!
  • 原文地址:https://www.cnblogs.com/lr599909928/p/12704466.html
Copyright © 2011-2022 走看看