This repository has been archived by the owner on Apr 29, 2020. It is now read-only.
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #87 from rehassachdeva/modular_multiplicative_inverse
Implement modular multiplicative inverse
- Loading branch information
Showing
3 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
""" | ||
Modular Multiplicative Inverse | ||
Complexity: O(m) | ||
Reference Used: | ||
http://www.geeksforgeeks.org/multiplicative-inverse-under-modulo-m/ | ||
""" | ||
|
||
|
||
def mod_inverse(a, m): | ||
""" | ||
Modular Multiplicative Inverse of two integers 'a' and 'm' is a positive | ||
integer 'x' less than m such that (ax) % m is 1. | ||
Finds modular inverse of 'a' modulo 'm' by checking for all integers from | ||
1 to 'm' and returns -1 if it doesn't exist. | ||
>>> from pydsa import mod_inverse | ||
>>> mod_inverse(3, 11) | ||
4 | ||
>>> mod_inverse(2, 12) | ||
-1 | ||
""" | ||
a = a % m | ||
for x in range(1, m): | ||
if (a*x) % m == 1: | ||
return x | ||
|
||
return -1 # modular inverse of 'a' modulo 'm' doesn't exist. |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from pydsa.mod_inverse import mod_inverse | ||
|
||
|
||
def test_mod_inverse(): | ||
assert mod_inverse(3, 13) == 9 | ||
assert mod_inverse(30, 120000) == -1 |