File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed
project_euler/problem_009 Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change 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 () = } " )
You can’t perform that action at this time.
0 commit comments