Greatest Common Divisor
Description
The Greatest Common Divisor (GCD), sometimes known as the highest common factor, is the largest number which divides two positive integers (a,b). For
a = 12, b = 8we can calculate the divisors of a:{1,2,3,4,6,12}and the divisors of b:{1,2,4,8}. Comparing these two, we see thatgcd(a,b) = 4. Now imagine we takea = 11, b = 17. Bothaandbare prime numbers. As a prime number has only itself and1as divisors,gcd(a,b) = 1. We say that for any two integersa,b, ifgcd(a,b) = 1thenaandbare coprime integers. Ifaandbare prime, they are also coprime. Ifais prime andb < athenaandbare coprime. 🔆 Think about the case foraprime andb > a, why are these not necessarily coprime? There are many tools to calculate the GCD of two integers, but for this task we recommend looking up Euclid's Algorithm. Try coding it up; it's only a couple of lines. Usea = 12, b = 8to test it. Now calculategcd(a,b)fora = 66528, b = 52920and enter it below.
Mr. Euclid, Sir
To answer the first quiz question, if b > a and a is prime, then it is possible that b is a multiple of a, so the GCD of these two numbers is a and they are not coprime.
Let's take a look at Euclid's Algorithm
Euclidean Algorithm
We are given two positive integers a and b, assume that a > b
Divide
a / bto get the remainderrand ifr = 0,bis the GCD ofa, bElse, replace
awithbandbwithr, then repeat
Implementation
def gcd(a, b):
# Only works if a > b
if a < b:
return gcd(b, a)
# Euclidean algorithm
while b != 0:
# Calculate r = a % b
# Set a = b
# Set b = r
a, b = b, a % b
return a
print(gcd(66528, 52920))Though of course, if you're lazy you can use an online tool
Flag
1512
Last updated