Skip to content
  • Sponsor TheAlgorithms/Python

  • Notifications You must be signed in to change notification settings
  • Fork 47.1k
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 59a0765

Browse files
committedMay 28, 2025·
Add new solution for the euler project problem 9 - precompute the squares.
1 parent a2fa32c commit 59a0765

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed
 

‎project_euler/problem_009/sol4.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
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 a*b*c.
14+
15+
References:
16+
- https://en.wikipedia.org/wiki/Pythagorean_triple
17+
"""
18+
19+
20+
def get_squares(n: int) -> list[int]:
21+
res = [0] * n
22+
for i in range(n):
23+
res[i] = i * i
24+
return res
25+
26+
27+
def solution(n: int = 1000) -> int:
28+
"""
29+
Precomputing squares and checking if a*a + b*b is the square by set look-up.
30+
31+
>>> solution(12)
32+
60
33+
>>> solution(36)
34+
1620
35+
"""
36+
37+
squares = get_squares(n)
38+
squares_set = set(squares)
39+
for i in range(1, n):
40+
for j in range(i, n):
41+
if (
42+
squares[i] + squares[j] in squares_set
43+
and squares[n - i - j] == squares[i] + squares[j]
44+
):
45+
return i * j * (n - i - j)
46+
47+
return -1
48+
49+
50+
if __name__ == "__main__":
51+
print(f"{solution() = }")

0 commit comments

Comments
 (0)
Please sign in to comment.