-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproblem143.ts
55 lines (48 loc) · 1.06 KB
/
problem143.ts
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
function gcd(a: number, b: number): number {
while (b != 0) {
[a, b] = [b, a % b];
}
return a;
}
function main(): number {
const LIMIT = 120000;
const pairs = {};
for (let i = 1; i < LIMIT; i++) {
const maxJ = Math.min(2 * i, LIMIT);
for (let j = i + 1; j < maxJ; j++) {
let x = j ** 2 - i ** 2;
let y = j * (2 * i - j);
const divisor = gcd(x, y);
x /= divisor;
y /= divisor;
const dx = x;
const dy = y;
if (x + y > LIMIT) {
break;
}
while (x + y <= LIMIT) {
(pairs[x] ||= new Set<number>()).add(y);
(pairs[y] ||= new Set<number>()).add(x);
x += dx;
y += dy;
}
}
}
const matches = new Set<number>();
for (const pStr in pairs) {
const p = +pStr;
for (const r of pairs[p]) {
for (const q of pairs[r]) {
if ((pairs[p].has(q)) && (p + q + r <= LIMIT)) {
matches.add(p + q + r);
}
}
}
}
let total = 0;
matches.forEach(function(x) {
total += x;
});
return total;
}
console.log(main());