Project Euler: Problem 9

https://projecteuler.net/problem=9

A Pythagorean triplet is a set of three natural numbers, $a < b < c$, for which,

$$a^2 + b^2 = c^2$$

For example, $3^2 + 4^2 = 9 + 16 = 25 = 5^2$.

There exists exactly one Pythagorean triplet for which $a + b + c = 1000$. Find the product abc.

I first created two lists, A and B, and set them to all values up to 1000.


In [50]:
A = range(1000)
B = range(1000)

Using two for loops, I looped through all the values in A, then all the values in B. Using the formulas for pythagorean triples from the wikipedia page about them, I used an if statement that said if the value in B was larger than the value in A, then to define three variables by their respective formula. These would be my pythagorean triples. Finally, I created another if statement that compared whether the sum of the pythagorean triples was 1000. If the sum was 1000, I printed the product.


In [51]:
for n in A:
    for m in B:
        if m > n:
            a = m ** 2 - n ** 2
            b = 2 * m * n
            c = m ** 2 + n ** 2
            if a + b + c == 1000:
                print(a * b * c)


31875000

In [ ]:
# This cell will be used for grading, leave it at the end of the notebook.