Created
September 6, 2018 18:37
-
-
Save senderista/e1210f65b8b584f735c2f763200c6a13 to your computer and use it in GitHub Desktop.
calculate multiplicative inverse of odd number mod 2^32 (in hex format)
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
import sys | |
# calculate multiplicative inverse of odd number mod 2^32 | |
# from https://groups.google.com/forum/m/#!msg/sci.crypt/UI-UMbUnYGk/hX2-wQVyE3oJ | |
def inverse(a): | |
x = a | |
assert (x * a & 0x7) == 1 | |
x += x - a * x * x | |
assert (x * a & 0x3F) == 1 | |
x += x - a * x * x | |
assert (x * a & 0xFFF) == 1 | |
x += x - a * x * x | |
assert (x * a & 0xFFFFFF) == 1 | |
x += x - a * x * x | |
assert (x * a & 0xFFFFFFFF) == 1 | |
return x & 0xFFFFFFFF | |
arg = int(sys.argv[1], 16) | |
print hex(inverse(arg)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment