Skip to content
This repository has been archived by the owner on Apr 29, 2020. It is now read-only.

Commit

Permalink
Merge pull request #87 from rehassachdeva/modular_multiplicative_inverse
Browse files Browse the repository at this point in the history
Implement modular multiplicative inverse
  • Loading branch information
goelakash committed May 21, 2016
2 parents 1c973f4 + dfcb43a commit a55c463
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions pydsa/__init__.py
Expand Up @@ -14,3 +14,4 @@
from .radix_sort import radix_sort
from .binary_tree import BTNode
from .gnome_sort import gnome_sort
from .mod_inverse import mod_inverse
30 changes: 30 additions & 0 deletions pydsa/mod_inverse.py
@@ -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.
6 changes: 6 additions & 0 deletions pydsa/tests/test_mod_inverse.py
@@ -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

0 comments on commit a55c463

Please sign in to comment.