Skip to content

Commit d37b92a

Browse files
committed
calculate modular multiplicative inverse
1 parent ab8fb0b commit d37b92a

File tree

3 files changed

+65
-1
lines changed

3 files changed

+65
-1
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ WIP, the descriptions of the below `unsolved yet` problems can be found in the [
8383
## [Number Theory](https://github.com/danrusei/algorithms_with_Go/tree/main/numbers)
8484

8585
- [] Modular Exponentiation
86-
- [] Modular multiplicative inverse
86+
- [x] [Modular multiplicative inverse](https://github.com/danrusei/algorithms_with_Go/tree/main/numbers/multiplicative)
8787
- [] Primality Test | Set 2 (Fermat Method)
8888
- [] Euler’s Totient Function
8989
- [x] [Sieve of Eratosthenes](https://github.com/danrusei/algorithms_with_Go/tree/main/numbers/eratosthenes)

numbers/multiplicative/README.md

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Modular multiplicative inverse
2+
3+
Source: [GeeksforGeeks](https://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/amp/)
4+
Source: [Wikipedia - Modular Multiplicative Inverse](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse)
5+
6+
Given two integers ‘a’ and ‘m’, find modular multiplicative inverse of ‘a’ under modulo ‘m’.
7+
The modular multiplicative inverse is an integer ‘x’ such that.
8+
9+
a x ≅ 1 (mod m)
10+
11+
The value of x should be in {0, 1, 2, … m-1}, i.e., in the range of integer modulo m.
12+
The multiplicative inverse of “a modulo m” exists if and only if a and m are relatively prime (i.e., if gcd(a, m) = 1).
13+
14+
## Example
15+
16+
> Input: a = 3, m = 11
17+
> Output: 4
18+
> Since (4*3) mod 11 = 1, 4 is modulo inverse of 3(under 11).
19+
> One might think, 15 also as a valid output as "(15*3) mod 11"
20+
is also 1, but 15 is not in ring {0, 1, 2, ... 10}, so not
21+
valid.
22+
>
23+
> Input: a = 10, m = 17
24+
> Output: 12
25+
> Since (10*12) mod 17 = 1, 12 is modulo inverse of 10(under 17).

numbers/multiplicative/main.go

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package main
2+
3+
import "fmt"
4+
5+
func modInverse(a int, m int) int {
6+
m0 := m
7+
x, y := 1, 0
8+
9+
if m == 1 {
10+
return 0
11+
}
12+
13+
for a > 1 {
14+
// q is quotient
15+
q := a / m
16+
t := m
17+
18+
// m is remainder now, process same as Euclid's algo
19+
m = a % m
20+
a = t
21+
t = y
22+
23+
// update y and x
24+
y = x - q*y
25+
x = t
26+
}
27+
28+
// make x positive
29+
if x < 0 {
30+
x += m0
31+
}
32+
33+
return x
34+
}
35+
36+
func main() {
37+
a, m := 3, 11
38+
fmt.Printf("Modular multiplicative inverse is %d\n", modInverse(a, m))
39+
}

0 commit comments

Comments
 (0)