COJ 1163 乘法逆元的求解

乘法逆元就是求一个 a/b = c(mod m)在已知a%m , b%m 的条件下 求c的解

 1 #include <cstdio>
 2 #include <cstring>
 3 
 4 using namespace std;
 5 #define ll long long
 6 const int N = 100005;
 7 int val[N];
 8 
 9 ll ex_gcd(ll a , ll b , ll &x , ll &y)
10 {
11     if(b == 0){
12         x=1 , y=0;
13         return a;
14     }
15     ll ans = ex_gcd(b,a%b,x,y);
16     ll t=x;
17     x=y,y=t-a/b*y;
18     return ans;
19 }
20 
21 ll inv(ll a , ll b , ll mod)
22 {
23     ll x , y;
24     ll d = ex_gcd(b,mod,x,y);
25     return a*x%mod;
26 }
27 
28 int main()
29 {
30     int n,m;
31     while(scanf("%d%d" , &n , &m ) == 2)
32     {
33         ll sum = 1;
34         for(int i=0 ; i<n ; i++){
35             scanf("%d" , val+i);
36             sum = (sum*val[i])%m;
37         }
38         for(int i=0 ; i<n ; i++){
39             ll ans = (inv(sum , (ll)val[i] , m)+m)%m;
40             if(i==0) printf("%lld" , ans);
41             else printf(" %lld" , ans);
42         }
43         printf("
");
44     }
45     return 0;
46 }
原文地址:https://www.cnblogs.com/CSU3901130321/p/4266682.html