Skip to content

Commit 9539ec0

Browse files
authored
Create TriangularNumberCheck.js
1 parent 5258492 commit 9539ec0

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

Maths/TriangularNumberCheck.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* github author: chrdek
3+
* license: GPL-3.0 or later
4+
*
5+
* @param {number} n = number to be determined whether is a triangular or not
6+
*
7+
* The function below is a mathematical algorithm to check if a given number n is a triangular number.
8+
* A triangular number is one that can be represented
9+
* in the form of the sum of consecutive positive integers starting from 1.
10+
*
11+
* Returns -1 for error input or negative numerical input, 0 for non-triangular
12+
* and an integer value if the number is triangular.
13+
*
14+
* The variable discriminant is calculated as the square root of (1 + 8 * n) and then its square root is taken again.
15+
* The expression Math.sqrt(1 + 8 * n) is the discriminant of the quadratic equation that represents triangular numbers.
16+
*
17+
**/
18+
19+
function IsTriangularNumber(n) {
20+
// Ensure the input n is a non-negative integer, retrurn -1 to indicate error.
21+
if (!Number.isInteger(n) || n < 0) {
22+
return -1;
23+
}
24+
25+
// Calculate the discriminant of the quadratic equation
26+
const discriminant = Math.sqrt(1 + 8 * n);
27+
28+
// Check if the discriminant is an integer
29+
if (discriminant % 1 === 0) {
30+
31+
// Return half of the integer value of the discriminant
32+
return Math.floor(discriminant / 2);
33+
} else {
34+
// If not a triangular number, return 0
35+
return 0;
36+
}
37+
}
38+
39+
export { IsTriangularNumber }

0 commit comments

Comments
 (0)