-
Notifications
You must be signed in to change notification settings - Fork 0
/
P9.js
63 lines (53 loc) · 1.32 KB
/
P9.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* ====== Problem 9 =================================== *
*
* A Pythagorean triplet is a set of three natural numbers,
* a < b < c, for which, a2 + b2 = c2
*
* 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.
*
* ========================================**/
function getSquareRoots(max) {
var sqrt = [], base = 1;
do {
sqrt.push(Math.pow(base, 2));
base++;
} while (base < max);
return sqrt;
}
function findTriplet() {
var sqrts = getSquareRoots(1000),
triplet = [];
for (var i = 0; i < sqrts.length; i++) {
for (var j = 0; j < sqrts.length; j++) {
var a, b, c;
c = Math.sqrt(sqrts[i] + sqrts[j]);
if (c % 1 === 0) {
a = Math.sqrt(sqrts[i]);
b = Math.sqrt(sqrts[j]);
if (a + b + c === 1000)
triplet = a * b * c;
}
}
}
return triplet;
}
function solution() {
var answer = findTriplet();
console.log(`The solution to problem 9 is: ${answer}`);
}
solution();
/* ====== Meta ========================================= *
*
* Estimated time of completion: 40 minutes
* Search engine used: Yes.
* Concepts learned: Math.sqrt.
*
* Additional notes:
*
* ========================================**/