2019-05-28 12:51:48 +00:00
|
|
|
# Python program to show the usage of Fermat's little theorem in a division
|
2020-06-16 08:09:19 +00:00
|
|
|
# According to Fermat's little theorem, (a / b) mod p always equals
|
|
|
|
# a * (b ^ (p - 2)) mod p
|
2019-05-28 12:51:48 +00:00
|
|
|
# Here we assume that p is a prime number, b divides a, and p doesn't divide b
|
|
|
|
# Wikipedia reference: https://en.wikipedia.org/wiki/Fermat%27s_little_theorem
|
|
|
|
|
|
|
|
|
|
|
|
def binary_exponentiation(a, n, mod):
|
2019-10-05 05:14:13 +00:00
|
|
|
if n == 0:
|
2019-05-28 12:51:48 +00:00
|
|
|
return 1
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
elif n % 2 == 1:
|
2019-05-28 12:51:48 +00:00
|
|
|
return (binary_exponentiation(a, n - 1, mod) * a) % mod
|
2019-07-10 20:09:24 +00:00
|
|
|
|
2019-05-28 12:51:48 +00:00
|
|
|
else:
|
|
|
|
b = binary_exponentiation(a, n / 2, mod)
|
|
|
|
return (b * b) % mod
|
|
|
|
|
|
|
|
|
|
|
|
# a prime number
|
|
|
|
p = 701
|
|
|
|
|
|
|
|
a = 1000000000
|
|
|
|
b = 10
|
|
|
|
|
|
|
|
# using binary exponentiation function, O(log(p)):
|
|
|
|
print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p)
|
|
|
|
|
|
|
|
# using Python operators:
|
|
|
|
print((a / b) % p == (a * b ** (p - 2)) % p)
|