1256 Multiplicative Inverses

Base Time Limit: 1 second Space Limit: 131072 KB Score: 0  Difficulty: Basic
 
Given two numbers M and N (M < N), and M and N are relatively prime, find a number K that satisfies 0 < K < N and K * M % N = 1, if there are multiple satisfying conditions, output the smallest.
 
Input
Enter 2 numbers M, N separated by spaces (1 <= M < N <= 10^9)
Output
Output a number K that satisfies 0 < K < N and K * M % N = 1. If there are multiple satisfying conditions, output the smallest one.
Input example
2 3
Output example
2 


Pure inversion element

 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 int exgcd(int a,int b,int &x,int &y){
 6     if(b==0){
 7         x=1,y=0;
 8         return a;
 9     }
10     int r = exgcd(b,a%b,x,y);
11     int t = x;
12     x = y;
13     y = t-(a/b)*y;
14     return r;
15 }
16 int main(){
17     int n,m;
18     cin>>n>>m;
19     int x,y;
20     int p = exgcd(n,m,x,y);
21     cout<<(x+m)%m<<endl;
22     return 0;
23 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324730774&siteId=291194637