Skip to content

Commit d02f6bb

Browse files
sarthaka13105arthak01dhruvmanila
authored
Added solution to Project Euler 69 (TheAlgorithms#2934)
* Added solution to Project Euler 69 * Accept edits from code review Co-authored-by: Dhruv <[email protected]> * Added doctests * Renaming and exception handling * Apply suggestions from code review Co-authored-by: Dhruv <[email protected]> * Edited mistake. Co-authored-by: formal-acc <[email protected]> Co-authored-by: Dhruv <[email protected]>
1 parent 60f9895 commit d02f6bb

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

project_euler/problem_69/__init__.py

Whitespace-only changes.

project_euler/problem_69/sol1.py

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
"""
2+
Totient maximum
3+
Problem 69: https://projecteuler.net/problem=69
4+
5+
Euler's Totient function, φ(n) [sometimes called the phi function],
6+
is used to determine the number of numbers less than n which are relatively prime to n.
7+
For example, as 1, 2, 4, 5, 7, and 8,
8+
are all less than nine and relatively prime to nine, φ(9)=6.
9+
10+
n Relatively Prime φ(n) n/φ(n)
11+
2 1 1 2
12+
3 1,2 2 1.5
13+
4 1,3 2 2
14+
5 1,2,3,4 4 1.25
15+
6 1,5 2 3
16+
7 1,2,3,4,5,6 6 1.1666...
17+
8 1,3,5,7 4 2
18+
9 1,2,4,5,7,8 6 1.5
19+
10 1,3,7,9 4 2.5
20+
21+
It can be seen that n=6 produces a maximum n/φ(n) for n ≤ 10.
22+
23+
Find the value of n ≤ 1,000,000 for which n/φ(n) is a maximum.
24+
"""
25+
26+
27+
def solution(n: int = 10 ** 6) -> int:
28+
"""
29+
Returns solution to problem.
30+
Algorithm:
31+
1. Precompute φ(k) for all natural k, k <= n using product formula (wikilink below)
32+
https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler's_product_formula
33+
34+
2. Find k/φ(k) for all k ≤ n and return the k that attains maximum
35+
36+
>>> solution(10)
37+
6
38+
39+
>>> solution(100)
40+
30
41+
42+
>>> solution(9973)
43+
2310
44+
45+
"""
46+
47+
if n <= 0:
48+
raise ValueError("Please enter an integer greater than 0")
49+
50+
phi = list(range(n + 1))
51+
for number in range(2, n + 1):
52+
if phi[number] == number:
53+
phi[number] -= 1
54+
for multiple in range(number * 2, n + 1, number):
55+
phi[multiple] = (phi[multiple] // number) * (number - 1)
56+
57+
answer = 1
58+
for number in range(1, n + 1):
59+
if (answer / phi[answer]) < (number / phi[number]):
60+
answer = number
61+
62+
return answer
63+
64+
65+
if __name__ == "__main__":
66+
print(solution())

0 commit comments

Comments
 (0)