|
| 1 | +""" |
| 2 | +Project Euler Problem 57: https://projecteuler.net/problem=57 |
| 3 | +It is possible to show that the square root of two can be expressed as an infinite |
| 4 | +continued fraction. |
| 5 | +
|
| 6 | +sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...))) |
| 7 | +
|
| 8 | +By expanding this for the first four iterations, we get: |
| 9 | +1 + 1 / 2 = 3 / 2 = 1.5 |
| 10 | +1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4 |
| 11 | +1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666... |
| 12 | +1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379... |
| 13 | +
|
| 14 | +The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion, |
| 15 | +1393/985, is the first example where the number of digits in the numerator exceeds |
| 16 | +the number of digits in the denominator. |
| 17 | +
|
| 18 | +In the first one-thousand expansions, how many fractions contain a numerator with |
| 19 | +more digits than the denominator? |
| 20 | +""" |
| 21 | + |
| 22 | + |
| 23 | +def solution(n: int = 1000) -> int: |
| 24 | + """ |
| 25 | + returns number of fractions containing a numerator with more digits than |
| 26 | + the denominator in the first n expansions. |
| 27 | + >>> solution(14) |
| 28 | + 2 |
| 29 | + >>> solution(100) |
| 30 | + 15 |
| 31 | + >>> solution(10000) |
| 32 | + 1508 |
| 33 | + """ |
| 34 | + prev_numerator, prev_denominator = 1, 1 |
| 35 | + result = [] |
| 36 | + for i in range(1, n + 1): |
| 37 | + numerator = prev_numerator + 2 * prev_denominator |
| 38 | + denominator = prev_numerator + prev_denominator |
| 39 | + if len(str(numerator)) > len(str(denominator)): |
| 40 | + result.append(i) |
| 41 | + prev_numerator = numerator |
| 42 | + prev_denominator = denominator |
| 43 | + |
| 44 | + return len(result) |
| 45 | + |
| 46 | + |
| 47 | +if __name__ == "__main__": |
| 48 | + print(f"{solution() = }") |
0 commit comments