Modular multiplicative inverse
Submissions: 1165   Accuracy:

42.2%

  Difficulty: Easy   Marks: 2

Given two integers ‘a’ and ‘m’. The task is to find modular multiplicative inverse of ‘a’ under modulo ‘m’.
Note: Print the smallest modular multiplicative inverse.

Input:
First line consists of T test cases. Only line of every test case consists of 2 integers 'a' and 'm'.

Output:
For each testcase, in a new line, print the modular multiplicative inverse if exists else print -1.

Constraints:
1 <= T <= 100
1 <= m <= 100
1 <= a <= m

Example:
Input:

2
3 11
10 17

Output:
4
12

Explanation:
Testcase1:

Input:  a = 3, m = 11
Output: 4
Since (4*3) mod 11 = 1, 4 is modulo inverse of 3
One might think, 15 also as a valid output as "(15*3) mod 11" 
is also 1, but 15 is not in ring {0, 1, 2, ... 10}, so not valid.

 

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Saksham Raj Seth
Author: saksham seth


If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.

to report an issue on this page.