MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / solution

Function solution

project_euler/problem_069/sol1.py:27–62  ·  view source on GitHub ↗

Returns solution to problem. Algorithm: 1. Precompute φ(k) for all natural k, k <= n using product formula (wikilink below) https://en.wikipedia.org/wiki/Euler%27s_totient_function#Euler's_product_formula 2. Find k/φ(k) for all k ≤ n and return the k that attains maximum >

(n: int = 10**6)

Source from the content-addressed store, hash-verified

25
26
27def 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
65if __name__ == "__main__":

Callers 1

sol1.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected