-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path042-coded-triangle-numbers.js
More file actions
55 lines (43 loc) · 1.01 KB
/
042-coded-triangle-numbers.js
File metadata and controls
55 lines (43 loc) · 1.01 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
/**
* Triangular number inverse
* Time Complexity: O(T log t)
* Space Complexity: O(1)
*/
function processData(input) {
const data = input.trim().split(/\s+/);
let idx = 0;
const T = Number(data[idx++]);
let out = [];
for (let i = 0; i < T; i++) {
const t = BigInt(data[idx++]);
const D = 1n + 8n * t;
const r = isqrt(D);
if (r * r !== D) {
out.push("-1");
continue;
}
const n = (r - 1n) / 2n;
if (n * (n + 1n) / 2n === t) out.push(n.toString());
else out.push("-1");
}
console.log(out.join("\n"));
};
function isqrt(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);
});