逆元

模板题链接

1、mod为质数下的普通逆元求法

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 int fp(int a, int b, int c){
 5     int res = 1;
 6     while(b){
 7         if(b & 1) res = (res * a) % c;
 8         a = (a * a) % c;
 9         b >>= 1;
10     }
11     return res;
12 }
13 
14 signed main(){
15     int n, p;
16     cin >> n >> p;
17     cout << fp(n, p - 2, p) << "\n";
18     
19     return 0; 
20 } 

2、o(n) 求 1 - n的逆元(模板题代码)

 1 #include <bits/stdc++.h>
 2 #define int long long
 3 using namespace std;
 4 
 5 const int N = 3e6 + 10;
 6 int n, p, inv[N];
 7 
 8 signed main(){
 9     
10     int n, p;
11     cin >> n >> p;
12     
13     inv[1] = 1;
14     for(int i = 2; i <= n; ++i){
15         inv[i] = (p - p / i * inv[p % i] % p) % p;
16     }
17     
18     for(int i = 1; i <= n; ++i) cout << inv[i] << "\n";
19     
20     return 0; 
21 } 

 

posted @ 2022-04-03 11:00  std&ice  阅读(52)  评论(0编辑  收藏  举报