General - Mathematics
Greatest Common Divisor
"The Greatest Common Divisor (GCD), sometimes known as the highest common factor, is the largest number which divides two positive integers (a,b).
Now calculate gcd(a,b)
for a = 66528, b = 52920
"
Lets make a simple implementation of Euclid's algorithm. All though it is always easier to use the math.gcd()
function.
Extended GCD
"Let a
and b
be positive integers.
The extended Euclidean algorithm is an efficient way to find integers u,v
such that
a * u + b * v = gcd(a,b)
Using the two primes p = 26513, q = 32321
, find the integers u,v
such that
p * u + q * v = gcd(p,q)
"
We can make a simple implementation like this:
Or if we want a all the imidate steps of the calculation, we can use print them as a table like this:
Modular Arithmetic 1
"Calculate the following integers:
11 ≡ x mod 6
8146798528947 ≡ y mod 17
The solution is the smaller of the two integers."
The first one is easy. 11 mod 6 = 5
The second one is not something to be calculated without help. So lets write a script to help us.
Modular Arithmetic 2
"A finite field Fp
is the set of integers {0,1,...,p-1}
, and under both addition and multiplication there is an inverse element b
for every element a
in the set, such that
a + b = 0
and a * b = 1
.
Lets say we pick p = 17
. Calculate 317 mod 17
. Now do the same but with 517 mod 17
.
What would you expect to get for 716 mod 17
? Try calculating that.
This interesting fact is known as Fermat's little theorem. We'll be needing this (and its generalisations) when we look at RSA cryptography.
Now take the prime p = 65537
. Calculate 27324678765465536 mod 65537
.
Did you need a calculator?"
Fermat's little theorem states that if the exponent is p - 1 then x is 1.
So here we simply get 1.
Modular Inverting
"As we've seen, we can work within a finite field Fp
, adding and multiplying elements, and always obtain another element of the field.
For all elements g
in the field, there exists a unique integer d
such that g * d ≡ 1 mod p
.
This is the multiplicative inverse of g
.
Example: 7 * 8 = 56 ≡ 1 mod 11
What is the inverse element: 3 * d ≡ 1 mod 13
?"
With Fermat's little theorem
Last updated