-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem57.py
46 lines (40 loc) · 1.06 KB
/
problem57.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
def solution(n: int = 1000) -> int:
"""Get the first one thousand expansions
Return how many fraction with more digits then denominator
"""
ans = 0
for i in range(1, n + 1):
if len(str(fraction(i)[0])) > len(str(fraction(i)[1])):
ans += 1
return ans
def fraction(n):
"""Get the Square root convergents
The Formula:
f(1) = (1,2)
f(2) = 1/ 2 + 1
f(n) = 1/ (2+f(n-1) - 1) +1 this is the formula
= (2+ f(n-1))/(1+ f(n-1))
f(n-1) = numerator / denominator
f(n) = 2*denominator + numerator / (numerator + denominator)
>>> fraction(1)
>>> (3,2)
>>> fraction(4)
>>> (41,29)
>>> fraction(8)
>>> (1393,985)
"""
# if n == 1:
# return (3, 2)
# return (
# fraction(n - 1)[1] * 2 + fraction(n - 1)[0],
# fraction(n - 1)[0] + fraction(n - 1)[1],
# )
if n == 1:
return 3, 2
p, q = 3, 2
for _ in range(2, n + 1):
p, q = 2 * q + p, p + q
return p, q
if __name__ == "__main__":
print(fraction(7))
print(solution())