charlesreid1.com blog

Euler's Theorem, the Totient Function, and Calculating Totients By Hand

Posted in Mathematics

permalink

Table of Contents

Introduction

Today we're going to delve into a little bit of number theory.

In number theory, we are usually dealing with modular arithmetic - expressions of the form:

$$ a \equiv b \mod m $$

or

$$ f(x) \equiv 0 \mod m $$

The mod indicates we're doing modular arithmetic, which is (formally) an algebraic system called a ring, which consists of the integers 0 through m.

An analogy to modular arithmetic is the way that the sine and cosine function "wrap around," and

$$ \sin \left( \dfrac{2 \pi}{3} \right) \equiv \sin \left( \dfrac{8 \pi}{3} \right) \equiv \sin \left( \dfrac{14 \pi}{3} \right) \equiv \dots $$

On a ring, this happens with the integers. So, for example,

$$ 2 \equiv 6 \equiv 10 \equiv \dots \mod 4 $$

Modular arithmetic uses the \(\equiv\) symbol, and not the \(=\) symbol, because we can't manipulate the left and right side using normal rules of algebra - solving equations on a ring requires some care.

The value of \(m\) need not be prime, generally, but if it is, we have some special properties that hold.

Complete and Reduced Residue Systems

Consider the ring of integers \(\mod 10\), which consists of the numbers

$$ \{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 \} $$

This is called the complete residue system mod 10. If we want to solve an equation like

$$ 2x \equiv 8 \mod 10 $$

we would normally just divide both sides by 2. But because of the "mod 10" we have to be a bit more careful. Dividing by 2 is just a way of saying, we want to multiply 2 by some number that will make 2 into 1.

However, because 2 is a factor of 10, there is no number in the complete residue system that will yield 1 mod 10 when we multiply it by 2:

$$ \begin{eqnarray*} 0 * 2 & \equiv & 0 \mod 10 \\ 1 * 2 & \equiv & 2 \mod 10 \\ 2 * 2 & \equiv & 4 \mod 10 \\ 3 * 2 & \equiv & 6 \mod 10 \\ 4 * 2 & \equiv & 8 \mod 10 \\ 5 * 2 \equiv 10 & \equiv & 0 \mod 10 \\ 6 * 2 \equiv 12 & \equiv & 2 \mod 10 \\ 7 * 2 \equiv 14 & \equiv & 4 \mod 10 \\ 8 * 2 \equiv 16 & \equiv & 6 \mod 10 \\ 9 * 2 \equiv 18 & \equiv & 8 \mod 10 \end{eqnarray*} $$

The same difficulty appears if we try and solve an equation like

$$ 5x \equiv 8 \mod 10 $$

for the same reason - 5 is a factor of 10, so it has no inverse mod 10.

Contrast that with solving an equation like

$$ 3x \equiv 8 \mod 10 $$

which, because 3 does not share any factors with 10, means we can find a number such that 3 times that number yields 1 mod 10:

$$ 3 \times 7 \equiv 21 \equiv 1 \mod 10 $$

so we can solve the equation by multiplying both sides by 7, the inverse of 3:

$$ \begin{eqnarray*} 3 x & \equiv & 8 \mod 10 \\ (7 \times 3) x & \equiv & (7 \times 8) \mod 10 \\ x &=& 56 \mod 10 \\ x &=& 6 \mod 10 \end{eqnarray*} $$

We can resolve this by creating a reduced residue system, which is a set of integers that have inverses mod 10. The reduced residue system consists of integers that

  • Have no common factors with the ring size \(m\)
  • Have no two elements that are congruent \mod m

So a reduced residue system \(\mod 10\) could be, for example,

$$ \{ 1, 3, 7, 9 \} $$

(other reduced residue systems are possible as well).

It is important to note that we do not include 0, in general, because 0 shares all factors with \(m\) - that is, every number in the complete residue system divides 0, so the greatest common factor of \(0\) and \(m\) is \(m\) and not 1!

(The only exception to this rule is \(m=1\), but this is a trivial case, since every integer is congruent mod 1.)

The reduced residue system has the property that any number in the complete residue system can be generated from the reduced residue system via addition.

Further, the size of the reduced residue system can be expressed using a function called the Euler totient function, denoted \(\phi(m)\). The totient function quantifies the number of integers less than \(m\) that are relatively prime with \(m\) (that is, two numbers such that the greatest common factor, denoted with the shorthand \((a,m)\), is 1).

Euler's Totient Function

Euler's totient function, \(\phi(m)\), turns out to be an extremely useful quantity in number theory. It also provides a quantitative measure of how divisible a number is. Take the two numbers 960 and 961 as examples:

$$ \phi(960) = 256 \qquad \phi(961) = 930 $$

from this, we can see that 960 has many more factors than 961. Here are their prime factorizations:

$$ \begin{eqnarray*} 960 = 2^6 \times 3 \times 5 \\ 961 = 31^2 \end{eqnarray*} $$

This means that the ring of integers mod 960 will have far more congruences that cannot be solved compared to the ring of integers mod 961.

Historical Note: The notation \(\phi(n)\) was first used by the mathematician Carl Friedrich Gauss in his incredible book Disquisitiones Arithmeticae, an important historical textbook that focused on gathering all of the results known to that point about number theory in a single work. (Gauss did omit the parenthesis, however, writing the totient function simply as \(\phi n\).)

Calculating the Totient Function by Hand

It may be obvious that the totient function is simple to compute using a computer; but the question naturally arises: can we compute totient functions for large integers by hand?

It turns out we can - we just need to be able to factor the number in question. (Note that this requirement is true generally; see the section on RSA Cryptography in a post to follow).

Let's first illustrate some rules for computing the totient function of composite numbers with some simple examples.

Totient Property: Prime Power

The first useful property is computing the totient function of a number that is a prime number raised to some power. Let's take the simple example of \(81 = 9^2 = 3^4\). We know that any number that shares factors with 81 is a multiple of 3 less than or equal to 81, which is the set of numbers

$$ \{ 1 \times 3, 2 \times 3, 3 \times 3, \dots, 3^{4-1} \times 3 \} $$

and there are \(3^{4-1}\) of these numbers. Thus, of all of the integers from \(1\) to \(3^4\), there are \(3^3\) of them that are not relatively prime with \(3^4\). So the totient function can be written:

$$ \begin{eqnarray*} \phi(81) &=& \phi(3^4) = 3^{4} - 3^{4-1} \\ \phi(81) &=& 81 - 27 \\ \phi(81) &=& = 54 \end{eqnarray*} $$

In general, if we are considering the totient function of a prime power \(p^k\), we can write the totient function as

$$ \phi(p^k) = p^{k} - p^{k-1} $$

Totient Property: Product of Primes

If we take a composite number like 20, we can split the totient function of 20 into the product of the totient function of the factors of 20:

$$ \begin{eqnarray*} 20 = 5 \times 4 \\ \phi(20) = \phi(5) \times \phi(4) \\ \phi(20) = 4 \times 2 = 8 \end{eqnarray*} $$

which is, indeed, the value of \(\phi(20)\). However, this does not hold generally, as we can see from computing the totient of 50:

$$ \begin{eqnarray*} 50 = 5 \times 10 \\ \phi(50) \neq \phi(5) \times \phi(10) \phi(50) \neq 4 \times 4 \phi(50) \neq 16 \end{eqnarray*} $$

In fact, the value of \(\phi(50)\) is 20, not 16! The problem is with our choice of factors, 5 and 10. These two numbers share a common factor of 5, meaning their totient functions do not account for all of the numbers that will be relatively prime with 50.

To fix this, we can further break down 50 into its prime factorization, and compute the totient function of those primes:

$$ \begin{eqnarray*} 50 &=& 2 \times 5^2 \\ \phi(50) &=& \phi(2) \times \phi(5^2) \\ \phi(50) &=& 1 \times ( 5^2 - 5 ) \\ \phi(50) &=& 1 \times 20 \\ \phi(50) &=& 20 \end{eqnarray*} $$

which gives us the correct result of 20.

Generalizing this rule, we can say that we can break down the totient function of a product of two numbers \(s \times t\) into the product of totient functions \(\phi(s)\) and \(\phi(t)\) only if the greatest common factor between \(s\) and \(t\) is 1.

Totient Example

Let's consider the following example: suppose we wish to compute

$$ \phi( 280 ) $$

We can start by recognizing some factors of 280 - we can pull out the factors 7 and 4, and 2 and 5. These can be further factored to yield the prime factorization of 280:

$$ 280 = 2^3 \times 5 \times 7 $$

Now we can use the property that the totient function of an integer \(m\) can be expressed as the product of the totient functions of the factors of \(m\). So we can write \(\phi(280)\) as any of the following equivalent expressions:

$$ \begin{eqnarray*} \phi(280) &=& \phi(10) \times \phi(7) \times \phi(2^2) \\ \phi(280) &=& \phi( 2^3 ) \times \phi(5) \times \phi(7) \end{eqnarray*} $$

Using the second expression, we know that

$$ \begin{eqnarray*} \phi(2^3) &=& (2^3 - 2^2) = 4 \\ \phi(5) &=& 4 \\ \phi(7) &=& 6 \end{eqnarray*} $$

for an overall totient function value of

$$ \begin{eqnarray*} \phi(280) &=& 4 \times 4 \times 6 \\ \phi(280) &=& 96 \end{eqnarray*} $$

which is indeed the correct result:

Totient function calculation with Wolfram Alpha

Tags:    mathematics    factors    number theory    euler   

Mad Combinatoric Castles

Posted in Mathematics

permalink

Table of Contents

Overview: The Problem

In an earlier post, I mentioned my efforts on Project Euler problems and the wide variety of problems there that can offer some profound mathematical insights.

Given that the first post covered Project Euler problem 1, I thought it would be nice if the next problem cranked up the difficulty factor by an order of magnitude. Project Euler Problem 502 is a very hairy combinatorics problem that required me to learn about a wide variety of combinatorial enumeration techniques.

Let's start with the problem statement.

Building Castles

Problem 502 is about building castles. The problem gives an \(M \times N\) rectangular grid, and asks us to count how many "castles" can be built on the rectangular grid, given its maximum height.

Here is how the game works:

First, start by defining a block as a rectangle of height 1, and an integer-valued length. A castle is a configuation of stacked blocks.

For a game grid of size \(M \times N\), we can construct castles according to the following rules:

  • Blocks can be placed on top of other blocks, but no sticking out past edge
  • All blocks aligned to grid
  • Two neighboring blocks must have 1 unit of space between them
  • Maximum achieved height of castle is EXACTLY M
  • Castle is made from even number of blocks

Here is an example W = 8, H = 5 castle given in more compact notation:

  #   # 
  #   ##
 ## # ##
##### ##
########

We can also build more complicated castles, like this 10 by 100 castle:

X       X      XX    X     XX   XX X X                          X XX          XX   XX  X     X   XXX
X       X      XX    X     XX X XX X X     X     X             XX XX          XX   XX  X     X   XXX
X      XX      XX    X     XX X XXXX X     X     X             XX XX          XX   XX  X     X   XXX
X      XX      XX    X     XX X XXXX X     X     X XXX         XX XX          XX X XX  X     X   XXX
X      XX     XXX    X     XX X XXXX X  X  X     X XXX X X     XX XX          XX X XX  X  X  X   XXX
X      XX  X  XXX  X X     XXXX XXXX X  XX X    XX XXX X X   X XX XX          XX XXXX  X XX XX  XXXX
X  XX  XX  X  XXX  X X     XXXX XXXX XX XX XX XXXX XXX X XXX X XX XX    X     XX XXXXX X XX XX XXXXX
X  XX  XXX X  XXX  X X   X XXXX XXXX XX XX XX XXXX XXXXX XXX XXXX XX  X X     XX XXXXX X XX XXXXXXXX
X XXXXXXXX X XXXXXXX X XXXXXXXX XXXXXXX XX XX XXXXXXXXXXXXXX XXXX XX XX X  XX XX XXXXXXXXXX XXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Our objective in this problem is to enumerate all possible castles. Let \(F(x,y)\) denote the number of unique castles with a width of x and a height of exactly y. The problem gives use the trivial number \(F(4,2) = 10\). The problem also gives \(F(13,10)\) and \(F(10,13)\), both of which are absolutely enormous numbers.

This should be your first giant red flag that manual enumeration through a traversal of combinatoric space is absolutely, positively out of the question. We'll explain why in more detail below, but suffice to say, there is a combinatoric explosion that occurs for castles larger than 10, so castles with a width of 1 trillion are going to get STUPID big.

Then we're given \(F(100,100)\), which is so enormous it has to be reported mod 1,000,000,007.

Finally, the problem asks us the following whopper of a question:

What is \(F(10^{12},100) + F(10^4, 10^4) + F(100,10^{12}) mod 1,000,000,007\)?

Whew.

The Scale of the Problem

For solving this problem it is important to take a step back and think through the size of the combinatoric space being searched, and what methods we have for carving out that space.

As already mentioned, the size of this problem - the actual number of castles - is surely larger than the Eddington numer, the number of protons in the known universe. The numbers of combinations are STUPID big. There's no way for the mind to fully wrap itself around the concept.

The huge numbers involved means, we must have a closed-form expression for \(F(x,y)\) that we can evaluate once to get each of the \(F(10^{12},100), F(10^4,10^4), F(100,10^{12})\) required by the answer. Doing so much as counting to 1 trillion takes minutes on modern computers, so if you're doing anything else 1 trillion times, you'll end up waiting a loooong time.

Generating Functions

As it turns out, there is indeed a combinatorial enumeration method that does not require explicitly finding or generating each permutation in order to count all permutations. I have covered generating functions on the charlesreid1.com wiki. The principal idea behind generating functions is the observation that we can rearrange the infinite series:

$$ G(z) = 1 + z + z^2 + z^3 + \dots $$

into the equation

$$ G(z) = \dfrac{1}{1-z} $$

This single identity leads to a whole family of solution techniques for generating functions. The basic idea is to start by writing the rules of your system (see above), then write a generating function that varies with characteristic variables of the problem (width and height in this case, possibly others), and last, combine the generating functions of different rules or objects into a single generating function.

Overview of Polyominoes

Let us begin by considering a two-dimensional grid \(\pi\) of points at positive integer coordinates, \(\pi = \mathbb{N} \times \mathbb{N}\).

Let a polyomino denote a two-dimensional shape formed by connecting contiguous unit square tiles together, all of which align to the 2D grid of integers \(\pi\).

(Granted, this definition sounds a bit pedantic, as we're just describing stackable squares, but we need to keep the definition general because there are many kinds of polyomonioes, and many rules that we can set for how we arrange them.)

If you have played Tetris before, or John Conway's Game of Life, you will recognize polyominoes from those contexts.

Now, we set up our generating function in terms of characteristics of the problem.

It is very important to note that, while most of the rules are fairly straightforward to translate into a polyomonio type of framework, Rule 6 is not. In fact, it is probably Rule 6 that makes Problem 502 so challenging. Were it not for Rule 6, this would be a nearly-trivial problem.

Let's review our castle construction rules and translate them into polyomino equivalents.

Castle Rules for Polyominoes

Generating Function Variables

We want to construct a multivariate ordinary generating function for our castles, since we have several variables we want to change, and get back a total count of castles.

The two most obvious variable choices for our generating function independent variables are width \(x\) and height \(y\). Surely, these must be in the final generating function.

However, this still doesn't give us enough information about the construction process from step to step. Imagine that we place the first block on row 1.

Then we may place as many blocks as we would like along row 2, wherever we would like (level 2 is the least restricted layer of the castle).

Now, when we get to row 3, we are only allowed to keep building where there is already an existing tower from the prior row. This means, we have to pass along information from the prior row - where the bricks are located and how many - so that we know where the next level may build towers.

This will remain an open question until we cover a few other representations of Problem 502 and ways of modeling it. Then we will cover what additional variables our generating function might need.

Rule 1: No Overhangs

Rule 1 stipulates that blocks can be placed on top of other blocks as long as nothing sticks out past the end or hags out.

This ensures that the resulting polyomino is column convex. Column convexity is the property that we can draw a vertical line through any column of the polyomino, and we only intersect the polyomino in two places. (No internal breaks.)

This rule stipulates what kind of polyomino constructions are allowed.

Rule 2: Snap to Grid

This rule is just saying that the unit squares in the castle problem match the unit squares of polyominoes, ensuring the problems are interchangeable.

Rule 3: Neighbor Blocks Need Space

Rule 3 is crucial for being able to count blocks. If two side-by-side contiguous unit squares could be either one or two blocks, this would make the final count of solutions much, much, much, much, much bigger than it should be.

Rule 4: Bottom Row is One Block

This is more of an accounting-based rule, but we define our castle construction process such that it begins with a completed row. This means that the number of blocks that we add on top of that single block must be odd overall.

Rule 5: Maximum Height is Exactly H

As it turns out, the last two rules are the toughest - in a sense, because they are global conditions on the combinatoric solution that is being counted. In other words, we will use generating functions to "construct" our combinatoric objects in a methodical way, and the challenge is on setting global conditions on the generating function's counted solutions.

Rule 6: Even Number of Blocks

Rule 6 is definitely what makes this problem difficult.

Our approach is going to involve coming up with a counting function - but this rule tells us that the counting function will need to have some way of accounting for the total number of blocks, and divide by or subtract a factor that accounts for castles with an odd number of blocks.

Don't Generate - Enumerate!

We mentioned above that the number of possibilities here is huge, so this combinatorics problem falls squarely in the realm of enumerating, not generating.

That being said, and keeping in mind that the problem size blows up rapidly, it can still be useful to write an algorithm to generate castles for small values of width and height, to test formulas for these small values (and uncover corner cases!).

See Project Euler/502 on the charlesreid1.com wiki for continued work on this problem.

Tags:    computer science    mathematics    factors    sequences    project euler   

Project Euler Problem 1

Posted in Mathematics

permalink

Table of Contents

Overview: The Problem

Project Euler is a website that provides mathematically-oriented programming problems. There are many (over 500) and they are a rich source of profound mathematical insights.

I have been considering a writeup that goes deep into a particular problem, so why not do it with problem 1?

Problem 1 of Project Euler asks:

Find the sum of all the multiples of 3 or 5 below 1000.

It is a pretty simple task - one of the first things covered in a decent programming course is the assortment of mathematical operators, including the modular operator and multiplication operator, useful here.

This problem is also a familiar problem in another guise - any computer science student who has solved a variant of the fizz buzz problem will recognize this task (in the fizz buzz problem, you print fizz every time a number is divisible by 3 and buzz every time it is divisible by 5, etc.)

It is a deceptively simple problem. In fact, it is so easy to solve with a computer that you almost lose a sense of what the manual process would look like. How might we perform this task by hand?

Finally, it is an example of a problem in which we are trying to find the number of outcomes of several classes of events, and some of the events are labeled with both classes. This means it will be important to learn and apply the Inclusion-Exclusion Principle. (Fortunately, this principle is fairly straightforward to apply.)

We will get to the algorithm to counting these factors by hand, and handling more complicated constraints as well, but first I'll address why this problem - this task - was deemed important enough to be the very first step that nearly everyone takes on their epic (or... not so epic) Project Euler journey.

Why This Problem?

The central task in this problem is to find multiples of a number \(k\), and count them. The task is simple enough (unlike later Project Euler questions, which can be downright frightening at times), but still requires knowledge of loops, operators, and basic algorithm design. It's no litmus test for whether you can solve Problem 100, but it gets you started.

The task at the heart of this problem - iterating through a list of multiples of a number - is at the heart of the Sieve of Eratosthenes algorithm, which in turn is at the heart of applied number theory. While it may not be the algorithm applied in practice, it is the first and most important algorithm number theorists learn.

It's also a first lesson in the subtleties of Project Euler problems - the eager but naive algorithm designer will count all multiples of 3, then all multiples of 5, forgetting that some repeat.

Project Euler Fail

Welcome to Project Euler.

Going Deeper: An Example

It's true that this problem seems a bit boring on its face. But let's dive deeper. Suppose I asked you to find the number of multiples of the integers 3 and 4, but not the integer 5, below 2,001 - and to do so without explicitly enumerating them with a computer.

To do this, we can express the problem in set notation. We have three sets, A, B, C, containing multiples of 3, 4, and 5, respectively. In set theory language, we wish to find

$$ ( A \bigcup B ) \backslash C $$

We can start by counting the sets A and B, as well as accounting for \(A \bigcap B\) (numbers that are multiples of both a and b).

Next, we can count \(A \bigcap C\) and \(B \bigcap C\), which are the multiples of a and b that we counted that we should not have because they are multiples of c.

Finally, we cannot forget \(A \bigcap B \bigcap C\) - numbers that have a, b, and c as multiples. This case is a bit tricky. Any item that is in \(A \bigcap B \bigcap C\) has already been removed - twice. The first time was when it was removed because it was in \(A \bigcap C\), and the second time was when it was removed because it was in \(B \bigcap C\). Therefore, we must add each of these items back in, to account for the double-removal and ensure these items are only removed once.

So we will add the items in \(A \bigcap B \bigcap C\) back into the final set.

Visually representing A, B, and C with a Venn diagram,

Project Euler Problem 1 Venn Diagram

To get back to the problem at hand, we can compute the size of these sets using the floor function. For example, the cardinality of A is:

$$ \mbox{card}(A) = \mbox{floor}\left( \frac{2001}{3} \right) = 667 $$
$$ \mbox{card}(B) = \mbox{floor}\left( \frac{2001}{4} \right) = 500 $$

Next, we subtract the duplicates (numbers with both A and B as factors):

$$ \mbox{card}(A \bigcap B) = \mbox{floor}\left( \frac{2001}{3 \cdot 4} \right) = 166 $$

Now subtract integers that have both a and c as multiples, or b and c as multiples:

$$ \mbox{card}(A \bigcap C) = \mbox{floor}\left( \frac{2001}{3 \cdot 5} \right) = 133 $$
$$ \mbox{card}(B \bigcap C) = \mbox{floor}\left( \frac{2001}{4 \cdot 5} \right) = 100 $$

And last but not least, those numbers with a, b, and c as factors were just removed twice, so we add them back in once:

$$ \mbox{card}(A \bigcap B \bigcap C) = \mbox{floor}\left( \frac{2001}{3 \cdot 4 \cdot 5} \right) = 33 $$

This gives a total number of multiples M below N with a or b as a factor, but not c:

$$ M = \mbox{floor}\left( \frac{N}{a} \right) + \mbox{floor}\left( \frac{N}{b} \right) - \mbox{floor}\left( \frac{N}{ab} \right) - \mbox{floor}\left( \frac{N}{ac} \right) - \mbox{floor}\left( \frac{N}{bc} \right) + \mbox{floor}\left( \frac{N}{abc} \right) $$

in our specific case,

$$ \begin{align} M &=& 667 + 500 - 166 - 133 - 100 + 33 \\ M &=& 801 \end{align} $$

Tags:    computer science    mathematics    factors    sequences    euler    project euler   

March 2022

How to Read Ulysses

July 2020

Applied Gitflow

September 2019

Mocking AWS in Unit Tests

May 2018

Current Projects

November 2017

A Hard(y) Math Problem