From fc95e7a91a4407ea5a293dbe80dc7a76d4af0976 Mon Sep 17 00:00:00 2001 From: Erfan Alimohammadi Date: Tue, 28 May 2019 17:21:48 +0430 Subject: [PATCH] Fermat's little theorem (#847) * Fix typo * Add fermat's little theorem * Update fermat_little_theorem.py * Fix comments * Add Wikipedia reference --- maths/fermat_little_theorem.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 maths/fermat_little_theorem.py diff --git a/maths/fermat_little_theorem.py b/maths/fermat_little_theorem.py new file mode 100644 index 00000000..93af9868 --- /dev/null +++ b/maths/fermat_little_theorem.py @@ -0,0 +1,30 @@ +# Python program to show the usage of Fermat's little theorem in a division +# According to Fermat's little theorem, (a / b) mod p always equals a * (b ^ (p - 2)) mod p +# 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): + + if (n == 0): + return 1 + + elif (n % 2 == 1): + return (binary_exponentiation(a, n - 1, mod) * a) % mod + + 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)