-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
inverse.go
26 lines (20 loc) · 724 Bytes
/
inverse.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// inverse.go
// description: Implementation of Modular Inverse Algorithm
// details:
// A simple implementation of Modular Inverse - [Modular Inverse wiki](https://en.wikipedia.org/wiki/Modular_multiplicative_inverse)
// author(s) [Taj](https://github.com/tjgurwara99)
// see inverse_test.go
package modular
import (
"errors"
"github.com/TheAlgorithms/Go/math/gcd"
)
var ErrorInverse = errors.New("no Modular Inverse exists")
// Inverse Modular function
func Inverse(a, m int64) (int64, error) {
gcd, x, _ := gcd.Extended(a, m)
if gcd != 1 || m == 0 {
return 0, ErrorInverse
}
return ((m + (x % m)) % m), nil // this is necessary because of Go's use of architecture specific instruction for the % operator.
}