Skip to content

Project Euler 57 - Square root convergents #3259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 16, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
48 changes: 48 additions & 0 deletions project_euler/problem_057/sol1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""
Project Euler Problem 57: https://projecteuler.net/problem=57
It is possible to show that the square root of two can be expressed as an infinite
continued fraction.

sqrt(2) = 1 + 1 / (2 + 1 / (2 + 1 / (2 + ...)))

By expanding this for the first four iterations, we get:
1 + 1 / 2 = 3 / 2 = 1.5
1 + 1 / (2 + 1 / 2} = 7 / 5 = 1.4
1 + 1 / (2 + 1 / (2 + 1 / 2)) = 17 / 12 = 1.41666...
1 + 1 / (2 + 1 / (2 + 1 / (2 + 1 / 2))) = 41/ 29 = 1.41379...

The next three expansions are 99/70, 239/169, and 577/408, but the eighth expansion,
1393/985, is the first example where the number of digits in the numerator exceeds
the number of digits in the denominator.

In the first one-thousand expansions, how many fractions contain a numerator with
more digits than the denominator?
"""


def solution(n: int = 1000) -> int:
"""
returns number of fractions containing a numerator with more digits than
the denominator in the first n expansions.
>>> solution(14)
2
>>> solution(100)
15
>>> solution(10000)
1508
"""
a, b = 1, 1
res = []
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Descriptive variable names would be awesome to work with :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great idea. I have made the replacements

a -> prev_numerator
b -> prev_denominator
res -> result

for i in range(1, n + 1):
numerator = a + 2 * b
denominator = a + b
if len(str(numerator)) > len(str(denominator)):
res.append(i)
a = numerator
b = denominator

return len(res)


if __name__ == "__main__":
print(f"{solution() = }")