Simple Number-Theoretic Insights with Python

maxvonhippel profile image Max von Hippel ・2 min read

Sometimes I learn about a new operator, or equivalence class, or some other such function from ZxZ to Z. Often looking at a grid of the numbers 0 - 9 on x and y axes illuminates interesting properties of such functionals. Here I will give some code with which to do just that.

Before I continue, here's a picture of I/O from the code I will be writing in this blog post / article / thing. I am including this at the start so that anyone who reads this knows what the goal of the code is to begin with.

I/O Examples

First let's define a few functionals, or functions, or operations, or whatever. This way we can quickly see the utility of our number_table code once we get to that.

Here are mine, but I encourage you to write your own. Note that I am coding in Python3. The code is simple and I think could be fairly easily ported to your language of choice.

# Euclid's Algorithm for Greatest Common Denominator (GCD):
# See https://en.wikipedia.org/wiki/Euclidean_algorithm for more info
euclid = lambda a, b: a if b == 0 else euclid(b, a % b)

# Two numbers are called "relatively prime" if their gcd is 1
relatively_prime = lambda a, b: int(euclid(a,b) == 1)

modulo = lambda a, b: a % b

and_ab = lambda a, b: a & b

Ok, now that we've got a couple cool little functions to investigate out of the way, let's get to the meat of making number grids. I like to colorize my number-grids by number, so I made a little function for coloring numbers in Python.

number_color = lambda n: "\033[1;3" + str(n) + ";40m " + str(n)

It doesn't really do anything for numbers greater than 8, but that's ok because if this bothers you then you can find a clever way to fix it. (This does not bother me.) Also, if you're interested in numbers bigger than 9 you'll have to modify my code a bit anyway, because I don't currently take that into account in the spacing of my table.

Now, here's my number_table code:

def number_table(method):
    # We assume method is defined
    print("    " + " ".join([number_color(n) for n in range(1,10)]))
    print("     _________________________")
    for a in range(1, 10):
        line = number_color(a) + ": "
        for b in range(1, 10):
            r = method(a, b)
            line += number_color(r) + " "

... And here is some more I/O:


Hope this proves useful!

Posted on Jan 22 '18 by:

maxvonhippel profile

Max von Hippel


Computer scientist / mathematician.


markdown guide