-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path045-triangular-pentagonal-and-hexagonal.js
More file actions
80 lines (70 loc) · 1.65 KB
/
045-triangular-pentagonal-and-hexagonal.js
File metadata and controls
80 lines (70 loc) · 1.65 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Triangular, Pentagonal, and Hexagonal
* Time Complexity: O( sqrt(N) * log N )
* Space Complexity: O(1)
*/
function processData(input) {
const parts = input.trim().split(/\s+/);
const N = BigInt(parts[0]);
const a = Number(parts[1]);
const b = Number(parts[2]);
const out = [];
if (a === 3 && b === 5) {
let n = 1n;
while (true) {
const P = n * (3n * n - 1n) / 2n;
if (P >= N) break;
if (isTriangular(P)) out.push(P.toString());
n++;
}
} else {
let n = 1n;
while (true) {
const H = n * (2n * n - 1n);
if (H >= N) break;
if (isPentagonal(H)) out.push(H.toString());
n++;
}
}
if (out[0] !== "1") out.unshift("1");
console.log(out.join("\n"));
};
function isSquareBig(n) {
if (n < 0n) return false;
let x = n;
let y = (x + 1n) >> 1n;
while (y < x) {
x = y;
y = (x + n / x) >> 1n;
}
return x * x === n;
};
function isTriangular(x) {
const D = 8n * x + 1n;
return isSquareBig(D);
};
function isPentagonal(x) {
const D = 24n * x + 1n;
if (!isSquareBig(D)) return false;
const r = sqrtBig(D);
return ((1n + r) % 6n === 0n);
};
function sqrtBig(n) {
if (n === 0n || n === 1n) return n;
let x = n;
let y = (x + 1n) >> 1n;
while (y < x) {
x = y;
y = (x + n / x) >> 1n;
}
return x;
};
process.stdin.resume();
process.stdin.setEncoding("ascii");
let _input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});