Erwin Janssen

Euler’s totient function

By Erwin Janssen

Euler’s totient function counts the number of positive integers up to a given integer nn that are coprime to nn. In other word, the number of integers kk in the range 1kn1 \le k \le n for which the greatest common divisor gcd(n,k)=1\gcd(n, k) = 1. The function is written using the Greek letter phi as φ(n)\varphi(n) or ϕ(n)\phi(n) and is often called Euler’s phi function.

An simple implementation of Euler’s totient function in Python is shown below:

import math

def phi(n):
    amount = 0

    for i in range(1, n + 1):
        if math.gcd(n, i) == 1:
            amount += 1

    return amount

Applications

One of the applications of Euler’s totient function is the RSA algorithm. Setting up a RSA system involves choosing large prime numbers pp and qq, computing n=pqn = p \cdot q and φ(n)\varphi(n). Because pp and qq are both prime numbers, φ(n)\varphi(n) can quickly be calculated: φ(n)=(p1)(q1)\varphi(n) = (p - 1)(q - 1).

Examples

If we have the product of two primes n=pq=3773=2701n = p \cdot q = 37 \cdot 73 = 2701, then we can compute φ(n)\varphi(n) as

φ(n)=(p1)(q1)=3672=2592 \varphi(n) = (p - 1)(q - 1) = 36 \cdot 72 = 2592