返回顶部

快速幂及快速幂求逆元

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 }

 

posted @ 2020-04-15 12:40  Rayotaku  阅读(265)  评论(0编辑  收藏  举报