Greatest Common Divisor in Python

Posted: , Last Updated:

# Recursive implementation to find the gcd (greatest common divisor) of two integers using the euclidean algorithm.
# For more than two numbers, e.g. three, you can box it like this: gcd(a,gcd(b,greatest_common_divisor.c)) etc.
# This runs in O(log(n)) where n is the maximum of a and b.
# :param a: the first integer
# :param b: the second integer
# :return: the greatest common divisor (gcd) of the two integers.


def gcd(a, b):
    # print("New *a* is " + str(a) + ", new *b* is " + str(b))
    if b == 0:
        # print("b is 0, stopping recursion, a is the gcd: " + str(a))
        return a
    # print("Recursing with new a = b and new b = a % b...")
    return gcd(b, a % b)

About the algorithm and language used in this code snippet:

Euclidean Greatest Common Divisor (GCD) Algorithm

The greatest common divisor of two numbers (in this case a and b) is the biggest number which both numbers can be divided by without a rest. This greatest common divisor algorithm, called the euclidean algorithm, determines this number. The greatest common divisor is also often abbreviated as gcd.

Description of the Algorithm

The basic principle behind thus gcd algorithm is to recursively determine the gcd of a and b by determining the gcd of b and a % b This hinges on the fact that the gcd of two numbers also divides their difference, e.g. the greatest common divisor of 16 and 24 (which is 8) is also the greatest common divisor of 24-16=8. This is therefore also true for 16 and 40 - in fact, rather than taking the difference, the remainder can also be used (repeatedly recursing on the difference will inevitable “pass” the remainder). In summary, the euclidean gcd algorithm uses these 2 steps:

  1. if a or b is 0, return the other one.
  2. Repeat with the new a as b and the new b as a % b.

Using the remainder has a much faster runtime compared to using the difference.

Example of the Algorithm

When computing the gcd of 1071 and 462, the following steps will be taken:

  1. a is 1071, new b is 462
  2. Recursing with new a = b and new b = a % b…
  3. New a is 462, new b is 147
  4. Recursing with new a = b and new b = a % b…
  5. New a is 147, new b is 21
  6. Recursing with new a = b and new b = a % b…
  7. New a is 21, new b is 0
  8. b is 0, stopping recursion, a is the gcd: 21

Runtime Complexity of the Algorithm

The runtime complexity of the Euclidean greatest common divisor algorithm is O(log(max(a,b))) (the logarithm of the maximum of the two numbers). Using the remainder rather than the difference is considerably faster - if the difference would’ve been used this greatest common divisor algorithm would’ve had a runtime of O(max(a,b))

Space Complexity of the Algorithm

The space complexity of the Euclidean greatest common divisor algorithm is equal to the runtime, since every recursive call is saved in the stack and everything else is constant.

Python

The Python Logo

Python™ is an interpreted language used for many purposes ranging from embedded programming to web development, with one of the largest use cases being data science.

Getting to “Hello World” in Python

The most important things first - here’s how you can run your first line of code in Python.

  1. Download and install the latest version of Python from python.org. You can also download an earlier version if your use case requires it - many technologies still require it due to the breaking changes introduced with Python 3.
  2. Open a terminal, make sure the python or python3 command is working, and that the command your’re going to be using is referring to the version you just installed by running python3 --version or python --version. If you’re getting a “command not found” error (or similar), try restarting your command line, and, if that doesn’t help, your computer. If the issue persists, here are some helpful StackOverflow questions for Windows, Mac and Linux.
  3. As soon as that’s working, you can run the following snippet: print("Hello World"). You have two options to run this: 3.1 Run python in the command line, just paste the code snippet and press enter (Press CTRL + D or write exit() and press enter to exit). 3.2 Save the snippet to a file, name it something ending with .py, e.g. hello_world.py, and run python path/to/hello_world.py. Tip: use the ls command (dir in Windows) to figure out which files are in the folder your command line is currently in.

That’s it! Notice how printing something to the console is just a single line in Python - this low entry barrier and lack of required boilerplate code is a big part of the appeal of Python.

Fundamentals in Python

To understand algorithms and technologies implemented in Python, one first needs to understand what basic programming concepts look like in this particular language.

Variables and Arithmetic

Variables in Python are really simple, no need to declare a datatype or even declare that you’re defining a variable; Python knows this implicitly.

a = 1
b = {'c':2}

print(a + b['c']) # prints 3

Arrays

Working with arrays is similarly simple in Python:

arr = ["Hello", "World"]

print(arr[0]) # Hello
print(arr[1]) # World
# print(arr[2]) # IndexError

arr.append("!")

print(arr[2]) # !

As those of you familiar with other programming language like Java might have already noticed, those are not native arrays, but rather lists dressed like arrays. This is evident by the fact that no size needs to be specified, and elements can be appended at will. In fact, print(type(arr)) prints <class 'list'>. This means that arrays in Python are considerably slower than in lower level programming languages. There are, however, packages like numpy which implement real arrays that are considerably faster.

Conditions

Just like most programming languages, Python can do if-else statements:

value = 1
if value==1:
    print("Value is 1")
elif value==2:
    print("Value is 2")
else:
    print("Value is something else")

Python does however not have case-statements that other languages like Java have. In my opinion, this can be excused by the simplicity of the if-statements which make the “syntactic sugar” of case-statements obsolete.

Loops

Python supports both for and while loops as well as break and continue statements. While it does not have do-while loops, it does have a number of built-in functions that make make looping very convenient, like ‘enumerate’ or range. Here are some examples:

value = 10
while value > 0:
    print(value)
    value -= 1

for index, character in enumerate("banana"):
    print("The %d-th letter is a %s" % (index + 1, character))

Note that Python does not share the common iterator-variable syntax of other languages (e.g. for(int i = 0; i < arr.length; i++) in Java) - for this, the enumerate function can be used.

Functions

Functions in Python are easily defined and, for better or worse, do not require specifying return or arguments types. Optionally, a default for arguments can be specified:

def print_something(something="Hello World"):
    print(something)
    return "Success"

print_something()
print(print_something("banana"))

(This will print “Hello World”, “Banana”, and then “Success”)

Syntax

As you might have noticed, Python does not use curly brackets ({}) to surround code blocks in conditions, loops, functions etc.; This is because Python depends on indentation (whitespace) as part of its syntax. Whereas you can add and delete any amount of whitespace (spaces, tabs, newlines) in Java without changing the program, this will break the Syntax in Python. This also means that semicolons are not required, which is a common syntax error in other languages.

Advanced Knowledge of Python

Python was first released in 1990 and is multi-paradigm, meaning while it is primarily imperative and functional, it also has object-oriented and reflective elements. It’s dynamically typed, but has started offering syntax for gradual typing since version 3.5. For more information, Python has a great Wikipedia article.