Skip to content

Commit 93174a1

Browse files
authored
Create 009.js
1 parent 810022a commit 93174a1

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

009.js

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/*
2+
Source: https://projecteuler.net/problem=9
3+
4+
Problem:
5+
"A Pythagorean triplet is a set of three natural numbers, a < b < c, for which a^2 + b^2 = c^2,
6+
7+
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.
8+
9+
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
10+
Find the product abc."
11+
12+
13+
My Algorithm:
14+
15+
1. Generate triplets using Euclid's formula for generating Pythagorean triples given an arbitrary pair of integers m and n:
16+
a = m^2 - n^2, b = 2*m*n, c = m^2 + n^2
17+
2. If a + b + c = 1000, return a*b*c
18+
*/
19+
20+
function solution() {
21+
for (let n = 1; n < 32; n++) { //32 is kinda arbitrary.
22+
for (let m = n+1; m < 32; m++) { //I did this because 32^2 is 1024, and since the max sum of a, b, and c is 1000 in the problem, generating triples up to m = 32 would cover all triples that might add up to 1000
23+
let a = Math.pow(m, 2) - Math.pow(n, 2)
24+
let b = (2 * m * n)
25+
let c = Math.pow(m, 2) + Math.pow(n, 2);
26+
27+
//https://en.wikipedia.org/wiki/Pythagorean_triple#Proof_of_Euclid's_formula
28+
//if you want to know how the formula works
29+
30+
if ((a + b + c) === 1000) { //if the sum is 1000..
31+
return (a*b*c); //we have the answer!
32+
}
33+
}
34+
}
35+
}
36+
37+
console.log(solution()); //outputs the answer!

0 commit comments

Comments
 (0)