projecteuler.net #9 in JavaScript

Ethan Jarrell
codeburst
Published in
3 min readJan 14, 2018

--

I mentioned in a previous post how I had recently started doing some of the projecteuler.net problems. They’re a blast, and I highly recommend checking them out if you haven’t already! In any case, here’s my solution and thought process for #9. The problem reads as follows:

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.

My initial thought on this is that I’m not working with numbers that are too large, which makes it easier. Since the sum is going to be 1000 of the Pythagorean triplet, a, b & c will also be less than 1000, obviously.

So like the above example, If I can create a loop, grab each number and compare it to each other number, I would end up with every combination of 3 numbers. Then I could select only the 3 that add up to 1000. Here’s how I wrote that in JavaScript:

let arrPythag = [];
for (var i = 1; i <= 1000; i++) {
arrPythag.push(i);
}

I create an initial array with a length of less than 1000.

let allTriplets = [];
for (var i = 0; i < arrPythag.length; i++) {
for (var k = 0; k < arrPythag.length; k++) {
for (var p = 0; p < arrPythag.length; p++) {
let aSquared = Math.pow(arrPythag[i],2);
let bSquared = Math.pow(arrPythag[k],2);
let cSquared = Math.pow(arrPythag[p],2);
if(aSquared + bSquared == cSquared && arrPythag[i] + arrPythag[k] + arrPythag[p] == 1000) {
allTriplets.push([arrPythag[i],arrPythag[k],arrPythag[p]]);
}
}
}
}

Then, in a triple nested for loop, I compare each iteration of each loop to the iteration of the next loops, and square the iteration. I have an empty array called “allTriplets”, and if a² + b² = c², then I want to grab it. However, the sum must also equal 1000, so I make a multi-conditional if statement. If it matches both conditions, I push each iteration into “allTriplets”.

At this point, “allTriplets” contains the three digits that I want, but I need to find their product.

console.log(allTriplets);
let product1 = allTriplets[0][0] * allTriplets[0][1] * allTriplets[0][2];
console.log(product1);

My initial solution wasn’t as pretty, but doing a triple nested for loop really makes it simple, so you can basically solve it in one function. In hindsight, I could probably have simplified it further, but including the multiplication and the loops in one function. But oh well.

--

--