Project Euler Problem 69 Solution

Project Euler Problem 69 Solution

Totient maximum

by {BetaProjects} | Project Euler & HackerRank

Project Euler Problem 69 Statement

Euler's Totient function, $\varphi(n)$ [sometimes called the phi function], is used to determine the number of numbers less than $n$ which are relatively prime to $n$. For example, as 1, 2, 4, 5, 7, and 8, are all less than nine and relatively prime to nine, $\varphi(9)=6$.

nRelatively PrimePHI(n)n/PHI(n)
2112
31,221.5
41,322
51,2,3,441.25
61,523
71,2,3,4,5,661.1666…
81,3,5,742
91,2,4,5,7,861.5
101,3,7,942.5

It can be seen that $n=6$ produces a maximum $\frac{n}{\varphi(n)}$ for $n\le 10$.

Find the value of $n\le 1,000,000$ for which $\frac{n}{\varphi(n)}$ is a maximum.

Solution

The totient function $\varphi(n)$, also known as Euler's totient function, is defined as the number of positive integers less than or equal to $n$ that are relatively prime to $n$. Two numbers are relatively prime if they share no common factors other than 1. By definition, 1 is considered relatively prime to all numbers. The integers that are both less than or equal to $n$ and relatively prime to $n$ are called totatives of $n$.

For example, for $n=24$, the totatives are $\{ 1, 5, 7, 11, 13, 17, 19, 23 \}$, so $\varphi(24) = 8$.

Our goal is to maximize the ratio $\frac{n}{\varphi(n)}$ for $n\le 10^6$. This involves understanding the formula for $\varphi(n)$, which is derived from the prime factorization of $n$:

$$\varphi(n) = n\prod\limits_{p|n} (1-\frac{1}{p})$$

where the product is taken over all distinct prime numbers $p$ that divide $n$. From this, the ratio becomes:

$$\frac{n}{\varphi(n)} = \prod\limits_{p|n} \frac{p}{p-1}$$

Our method solves this problem by multiplying distinct, consecutive primes starting from 2 until we reach, but do not exceed, the limit, L, of 1,000,000. This reduces to simply finding the closest primorial to our limit and never having to calculate any totients; a time–consuming proposition.

HackerRank version

HackerRank Project Euler 69 increases the limit to 1018.

Python Source Code

def f(N):
    maxn = 1
    for p in primes:
        if maxn*p >= N: return maxn
        maxn *= p
    return None

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53]
for _ in range(int(input())):
    print(f(int(input())))	

Last Word