Skip to content

Instantly share code, notes, and snippets.

@mcichecki
Created June 23, 2018 11:03
Show Gist options
  • Save mcichecki/d081022833e10af3105a3af08e9aa6d0 to your computer and use it in GitHub Desktop.
Save mcichecki/d081022833e10af3105a3af08e9aa6d0 to your computer and use it in GitHub Desktop.
Modular multiplicative inverse - Swift implementation
/*
given a and m, function finds x for a * x = 1 (mod m)
24 * x = 1 (mod 5)
24 = x*exp(-1) (mod 5)
x = 4
modInverse(a: 24, m: 5) returns optional(4)
*/
func modInverse(a: Int, m: Int) -> Int? {
let tmp = a % m
for i in 1..<m {
if (tmp * i % m == 1) {
return i;
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment