Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 55db5a1

Browse files
mindauglMaximSmolskiy
andauthored
Add new solution for the euler project problem 9 (#12771)
* Add new solution for the euler project problem 9 - precompute the squares. * Update sol4.py * updating DIRECTORY.md * Update sol4.py * Update sol4.py * Update sol4.py --------- Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru> Co-authored-by: MaximSmolskiy <MaximSmolskiy@users.noreply.github.com>
1 parent dc1b200 commit 55db5a1

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

‎DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -956,6 +956,7 @@
956956
* [Sol1](project_euler/problem_009/sol1.py)
957957
* [Sol2](project_euler/problem_009/sol2.py)
958958
* [Sol3](project_euler/problem_009/sol3.py)
959+
* [Sol4](project_euler/problem_009/sol4.py)
959960
* Problem 010
960961
* [Sol1](project_euler/problem_010/sol1.py)
961962
* [Sol2](project_euler/problem_010/sol2.py)

‎project_euler/problem_009/sol4.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
Project Euler Problem 9: https://projecteuler.net/problem=9
3+
4+
Special Pythagorean triplet
5+
6+
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
7+
8+
a^2 + b^2 = c^2.
9+
10+
For example, 3^2 + 4^2 = 9 +たす 16 = 25 = 5^2.
11+
12+
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
13+
Find the product abc.
14+
15+
References:
16+
- https://en.wikipedia.org/wiki/Pythagorean_triple
17+
"""
18+
19+
20+
def get_squares(n: int) -> list[int]:
21+
"""
22+
>>> get_squares(0)
23+
[]
24+
>>> get_squares(1)
25+
[0]
26+
>>> get_squares(2)
27+
[0, 1]
28+
>>> get_squares(3)
29+
[0, 1, 4]
30+
>>> get_squares(4)
31+
[0, 1, 4, 9]
32+
"""
33+
return [number * number for number in range(n)]
34+
35+
36+
def solution(n: int = 1000) -> int:
37+
"""
38+
Precomputing squares and checking if a^2 + b^2 is the square by set look-up.
39+
40+
>>> solution(12)
41+
60
42+
>>> solution(36)
43+
1620
44+
"""
45+
46+
squares = get_squares(n)
47+
squares_set = set(squares)
48+
for a in range(1, n // 3):
49+
for b in range(a + 1, (n - a) // 2 + 1):
50+
if (
51+
squares[a] + squares[b] in squares_set
52+
and squares[n - a - b] == squares[a] + squares[b]
53+
):
54+
return a * b * (n - a - b)
55+
56+
return -1
57+
58+
59+
if __name__ == "__main__":
60+
print(f"{solution() = }")

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /