TheAlgorithms-Python

Форк
0
50 строк · 1.4 Кб
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: 1 sec
22
"""
23

24
import numpy as np
25

26

27
def solution(limit: int = 1_000_000) -> int:
28
    """
29
    Returns an integer, the solution to the problem
30
    >>> solution(10)
31
    31
32
    >>> solution(100)
33
    3043
34
    >>> solution(1_000)
35
    304191
36
    """
37

38
    # generating an array from -1 to limit
39
    phi = np.arange(-1, limit)
40

41
    for i in range(2, limit + 1):
42
        if phi[i] == i - 1:
43
            ind = np.arange(2 * i, limit + 1, i)  # indexes for selection
44
            phi[ind] -= phi[ind] // i
45

46
    return np.sum(phi[2 : limit + 1])
47

48

49
if __name__ == "__main__":
50
    print(solution())
51

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.