Modular Inverse Time Limit: 2 seconds memory limit: 65536 KB
The modular multiplicative inverse of an integerAModuloMIs an integerXSuch thata-1≡x (mod m)
. This is equivalentax≡1 (mod m)
.
Input
There are multiple test cases. The first line of input is an integerT≈ 2000 indicating the number of test cases.
Each test case contains two integers 0 <A≤ 1000 and 0 <M≤ 1000.
Output
For each test case, output the smallest positiveX. If suchXDoesn' t exist, output "not exist ".
Sample Input
33 114 125 13
Sample output
4Not Exist8
References
- Http://en.wikipedia.org/wiki/Modular_inverse
Author:Wu, zejun
Contest:The 9th Zhejiang Provincial Collegiate Programming Contest
Simply put, given n, m is required to obtain an X so that (N * X) % m = 1. If X has the smallest positive integer x, otherwise not exist is output.
Note that M = 1, because the modulo value of any number on 1 is equal to 0, but the minimum positive integer must be output here, so 1 is output.
1 # include <cstdio> 2 # include <cstring> 3 # include <stdlib. h> 4 # include <algorithm> 5 using namespace STD; 6 int gcd (int A, int B) 7 {8 return B? Gcd (B, A % B): A; 9} 10 int main () 11 {12 // freopen ("in.txt", "r", stdin); 13 int Kase; 14 scanf ("% d", & Kase); 15 while (Kase --) 16 {17 int n, m; 18 scanf ("% d", & N, & M); 19 20 if (M = 1) // when M = 1, the modulo of the number to 1 is equal to 0. This number exists, but the smallest positive integer must be output here, therefore, output 121 {printf ("1 \ n"); continue;} 22 23 int GCD = gcd (n, m); 24 25 if (GCD> 1) 26 {printf ("not exist \ n"); continue;} 27 28 else29 for (INT I = 1; I <= 1000; I ++) 30 if (n * I) % m = 1) 31 {printf ("% d \ n", I); break;} 32} 33 return 0; 34}
View code