Problem 9

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

a2 + b2 = c2

For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Solution 1: Stupid Brute Forcing

import math


def tri(n): for i in range(1, n): for j in range(i+1, n): if i + j + math.sqrt(i**2 + j**2) == float(n): return i*j*int(math.sqrt(i**2 + j**2))

print(tri(1000))

This run: ~0.3749995231628418. It is much less stupid than I imagined at first.
The output: 31875000

Just making n to (n - i)//2 in the second for loop for making hypotanous bigger.

initial = time()


def tri(n): for i in range(1, n): for j in range(i, (n - i)//2): # changed from n if i + j + math.sqrt(i**2 + j**2) == n: return i*j*int(math.sqrt(i**2 + j**2))

print(tri(1000))


This run: ~0.1249995231628418. Halved.
The output: 31875000


Solution 2: Smartest way

[The m,n formula for generating Pythagorean Triples. Read here!](https://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Pythag/pythag.html#section2.3)


def tri(num): for m in range(num): for n in range(1,m): a = m**2-n**2 b = 2*m*n c = m**2+n**2 tot = a + b + c
# We got primitive which can # be multiplied to make answer if not num%tot: return (num // tot)**3 * (a * b * c)

print(tri(1000))


This run: ~0.0. That is it.
The output: 31875000