|
| 1 | +""" |
| 2 | +Project Euler Problem 72: https://projecteuler.net/problem=72 |
| 3 | +
|
| 4 | +Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, |
| 5 | +it is called a reduced proper fraction. |
| 6 | +
|
| 7 | +If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, |
| 8 | +we get: |
| 9 | +
|
| 10 | +1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, |
| 11 | +4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 |
| 12 | +
|
| 13 | +It can be seen that there are 21 elements in this set. |
| 14 | +
|
| 15 | +How many elements would be contained in the set of reduced proper fractions |
| 16 | +for d ≤ 1,000,000? |
| 17 | +""" |
| 18 | + |
| 19 | + |
| 20 | +def solution(limit: int = 1000000) -> int: |
| 21 | + """ |
| 22 | + Return the number of reduced proper fractions with denominator less than limit. |
| 23 | + >>> solution(8) |
| 24 | + 21 |
| 25 | + >>> solution(1000) |
| 26 | + 304191 |
| 27 | + """ |
| 28 | + primes = set(range(3, limit, 2)) |
| 29 | + primes.add(2) |
| 30 | + for p in range(3, limit, 2): |
| 31 | + if p not in primes: |
| 32 | + continue |
| 33 | + primes.difference_update(set(range(p * p, limit, p))) |
| 34 | + |
| 35 | + phi = [float(n) for n in range(limit + 1)] |
| 36 | + |
| 37 | + for p in primes: |
| 38 | + for n in range(p, limit + 1, p): |
| 39 | + phi[n] *= 1 - 1 / p |
| 40 | + |
| 41 | + return int(sum(phi[2:])) |
| 42 | + |
| 43 | + |
| 44 | +if __name__ == "__main__": |
| 45 | + print(f"{solution() = }") |
0 commit comments