Skip to content

Commit cdc6bd1

Browse files
authored
add solution for project_euler/problem_009
1 parent e9e7c96 commit cdc6bd1

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

project_euler/problem_009/sol4.py

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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+
Solution:
16+
Let's consider the constraint a + b + c = n (n = 1000) and think of the values
17+
we can get for each variable while satisfying the constraint. We can have:
18+
a = 333, b = 333, c = 334
19+
a = 500, b = 500, c = 0
20+
a = 5, b = 990, c = 5
21+
and various other combinations. Note that at least one value has to be
22+
at least 333 (or n//3 as n = 1000). Raising at least one variable to
23+
nearly n//2 value decreases another variable's value.
24+
25+
When we introduce the constraint a < b < c, we will have combinations of
26+
three distinct values. The triplet cannot form an isoceles triangle.
27+
Thus, we observe:
28+
a = 167, b = 333, c = 500
29+
a = 331, b = 333, c = 336
30+
a = 1, b = 499, c = 500
31+
If n is even, only two variables will be odd or all will have even values.
32+
Furthermore, the constraint a**2 + b**2 = c**2 suggest the if 'a' or 'b' is odd
33+
then 'c' is odd too and vice versa.
34+
35+
Therefore, our solution will:
36+
- use "a + b + c = 1000" to elimiate 'c' (and hence remove a third for loop)
37+
by having "c = 1000 - a - b" and hence comparing a**2 + b**2 = (1000-a-b)**2
38+
- have an odd number and an even number to ensure 'a' and 'b' are distinct
39+
- iterate for values of 'b' from (n//2 - 1) to (n//3 + 1) to ensure
40+
that minimum value of 'c' can be (n//2) and 'a' can be (n//3) at maximum,
41+
thus satisfying the constraint a < b < c and a + b + c = n
42+
43+
References:
44+
- https://en.wikipedia.org/wiki/Pythagorean_triple
45+
"""
46+
47+
48+
def solution(n: int = 1000) -> int:
49+
"""
50+
Returns the product of a,b,c which are Pythagorean Triplet that satisfies
51+
the following:
52+
1. a < b < c
53+
2. a**2 + b**2 = c**2
54+
3. a + b + c = 1000
55+
56+
>>> solution()
57+
31875000
58+
>>> solution(910)
59+
11602500
60+
>>> solution(2002)
61+
123543420
62+
"""
63+
64+
for b in range(n // 2 - 1, n // 3, -2):
65+
for a in range(b - 1, 0, -2):
66+
c = n - b - a
67+
if b > c: # constraint a < b < c should be satisfied
68+
continue
69+
if a**2 + b**2 == c**2: # is it a pythagorean triplet
70+
return a * b * c
71+
72+
73+
if __name__ == "__main__":
74+
print(f"{solution() = }")

0 commit comments

Comments
 (0)