Skip to content

Commit d73247d

Browse files
c-utkarshstokhos
authored andcommitted
Add a solution to Project Euler 72 (TheAlgorithms#2940)
* Added Problem 72 * Removed args from solution() * Incorporated the suggested changes
1 parent 565a7ad commit d73247d

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

project_euler/problem_72/__init__.py

Whitespace-only changes.

project_euler/problem_72/sol1.py

+46
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
"""
2+
Problem 72 Counting fractions: https://projecteuler.net/problem=72
3+
4+
Description:
5+
6+
Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1,
7+
it is called a reduced proper fraction.
8+
If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we
9+
get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7,
10+
3/4, 4/5, 5/6, 6/7, 7/8
11+
It can be seen that there are 21 elements in this set.
12+
How many elements would be contained in the set of reduced proper fractions for
13+
d ≤ 1,000,000?
14+
15+
Solution:
16+
17+
Number of numbers between 1 and n that are coprime to n is given by the Euler's Totient
18+
function, phi(n). So, the answer is simply the sum of phi(n) for 2 <= n <= 1,000,000
19+
Sum of phi(d), for all d|n = n. This result can be used to find phi(n) using a sieve.
20+
21+
Time: 3.5 sec
22+
"""
23+
24+
25+
def solution(limit: int = 1_000_000) -> int:
26+
"""
27+
Returns an integer, the solution to the problem
28+
>>> solution(10)
29+
31
30+
>>> solution(100)
31+
3043
32+
>>> solution(1_000)
33+
304191
34+
"""
35+
36+
phi = [i - 1 for i in range(limit + 1)]
37+
38+
for i in range(2, limit + 1):
39+
for j in range(2 * i, limit + 1, i):
40+
phi[j] -= phi[i]
41+
42+
return sum(phi[2 : limit + 1])
43+
44+
45+
if __name__ == "__main__":
46+
print(solution())

0 commit comments

Comments
 (0)