|
| 1 | +""" |
| 2 | +Project Euler Problem 64: https://projecteuler.net/problem=64 |
| 3 | +
|
| 4 | +All square roots are periodic when written as continued fractions. |
| 5 | +For example, let us consider sqrt(23). |
| 6 | +It can be seen that the sequence is repeating. |
| 7 | +For conciseness, we use the notation sqrt(23)=[4;(1,3,1,8)], |
| 8 | +to indicate that the block (1,3,1,8) repeats indefinitely. |
| 9 | +Exactly four continued fractions, for N<=13, have an odd period. |
| 10 | +How many continued fractions for N<=10000 have an odd period? |
| 11 | +
|
| 12 | +References: |
| 13 | +- https://en.wikipedia.org/wiki/Continued_fraction |
| 14 | +""" |
| 15 | + |
| 16 | +from math import floor, sqrt |
| 17 | + |
| 18 | + |
| 19 | +def continuous_fraction_period(n: int) -> int: |
| 20 | + """ |
| 21 | + Returns the continued fraction period of a number n. |
| 22 | +
|
| 23 | + >>> continuous_fraction_period(2) |
| 24 | + 1 |
| 25 | + >>> continuous_fraction_period(5) |
| 26 | + 1 |
| 27 | + >>> continuous_fraction_period(7) |
| 28 | + 4 |
| 29 | + >>> continuous_fraction_period(11) |
| 30 | + 2 |
| 31 | + >>> continuous_fraction_period(13) |
| 32 | + 5 |
| 33 | + """ |
| 34 | + numerator = 0.0 |
| 35 | + denominator = 1.0 |
| 36 | + ROOT = int(sqrt(n)) |
| 37 | + integer_part = ROOT |
| 38 | + period = 0 |
| 39 | + while integer_part != 2 * ROOT: |
| 40 | + numerator = denominator * integer_part - numerator |
| 41 | + denominator = (n - numerator ** 2) / denominator |
| 42 | + integer_part = int((ROOT + numerator) / denominator) |
| 43 | + period += 1 |
| 44 | + return period |
| 45 | + |
| 46 | + |
| 47 | +def solution(n: int = 10000) -> int: |
| 48 | + """ |
| 49 | + Returns the count of numbers <= 10000 with odd periods. |
| 50 | + This function calls continuous_fraction_period for numbers which are |
| 51 | + not perfect squares. |
| 52 | + This is checked in if sr - floor(sr) != 0 statement. |
| 53 | + If an odd period is returned by continuous_fraction_period, |
| 54 | + count_odd_periods is increased by 1. |
| 55 | +
|
| 56 | + >>> solution(2) |
| 57 | + 1 |
| 58 | + >>> solution(5) |
| 59 | + 2 |
| 60 | + >>> solution(7) |
| 61 | + 2 |
| 62 | + >>> solution(11) |
| 63 | + 3 |
| 64 | + >>> solution(13) |
| 65 | + 4 |
| 66 | + """ |
| 67 | + count_odd_periods = 0 |
| 68 | + for i in range(2, n + 1): |
| 69 | + sr = sqrt(i) |
| 70 | + if sr - floor(sr) != 0: |
| 71 | + if continuous_fraction_period(i) % 2 == 1: |
| 72 | + count_odd_periods += 1 |
| 73 | + return count_odd_periods |
| 74 | + |
| 75 | + |
| 76 | +if __name__ == "__main__": |
| 77 | + print(f"{solution(int(input().strip()))}") |
0 commit comments