Created
June 23, 2018 11:03
-
-
Save mcichecki/d081022833e10af3105a3af08e9aa6d0 to your computer and use it in GitHub Desktop.
Modular multiplicative inverse - Swift implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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