TheAlgorithms-Python
50 строк · 1.4 Кб
1"""
2Problem 72 Counting fractions: https://projecteuler.net/problem=72
3
4Description:
5
6Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1,
7it is called a reduced proper fraction.
8If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we
9get: 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,
103/4, 4/5, 5/6, 6/7, 7/8
11It can be seen that there are 21 elements in this set.
12How many elements would be contained in the set of reduced proper fractions for
13d ≤ 1,000,000?
14
15Solution:
16
17Number of numbers between 1 and n that are coprime to n is given by the Euler's Totient
18function, phi(n). So, the answer is simply the sum of phi(n) for 2 <= n <= 1,000,000
19Sum of phi(d), for all d|n = n. This result can be used to find phi(n) using a sieve.
20
21Time: 1 sec
22"""
23
24import numpy as np25
26
27def solution(limit: int = 1_000_000) -> int:28"""29Returns an integer, the solution to the problem
30>>> solution(10)
3131
32>>> solution(100)
333043
34>>> solution(1_000)
35304191
36"""
37
38# generating an array from -1 to limit39phi = np.arange(-1, limit)40
41for i in range(2, limit + 1):42if phi[i] == i - 1:43ind = np.arange(2 * i, limit + 1, i) # indexes for selection44phi[ind] -= phi[ind] // i45
46return np.sum(phi[2 : limit + 1])47
48
49if __name__ == "__main__":50print(solution())51