Modular exponentiation pow with 3 arguments
suggest changeSupplying pow() with 3 arguments pow(a, b, c) evaluates the modular exponentiation ab mod c:
pow(3, 4, 17) # 13
# equivalent unoptimized expression:
3 ** 4 % 17 # 13
# steps:
3 ** 4 # 81
81 % 17 # 13
For built-in types using modular exponentiation is only possible if:
- First argument is an
int - Second argument is an
int - Third argument is an
intother than0
Since Python 3.8, a negative second argument is allowed when the base has a modular inverse for that modulus. Otherwise pow raises ValueError.
For example one can use the 3-argument form of pow to define a modular inverse function:
def modular_inverse(x, p):
"""Find a such that a·x ≡ 1 (mod p), assuming p is prime."""
return pow(x, p-2, p)
[modular_inverse(x, 13) for x in range(1,13)]
# Out: [1, 7, 9, 10, 8, 11, 2, 5, 3, 4, 6, 12]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents