- Build-up
- 1 + 2 + 3 + 4 = 10
- Verdict
- Fourth triangular number (four rows).
Check Triangular Number in JavaScript
What you’ll learn
- What a triangular number means without jargon: adding 1, then 2, then 3, and so on.
- The neat formula Tk = k(k+1)/2 and how it connects to the same picture.
- Two complete JavaScript programs: test one value, then print every triangular number from 1 to 50.
- A live preview, common edge cases, and time/space notes for exams.
Overview
Imagine building a triangle with rows of dots: one dot on top, two in the next row, three in the row below that, and so on. The total number of dots after each full row is a triangular number. This page shows how to ask: “Is this whole number one of those totals?” using short C programs.
Loop you can explain aloud
Keep a running total. Add 1, then 2, then 3, until you either match the target or pass it. No advanced math library is required.
Live preview
Watch the running total grow step by step for values like 6, 10, or 7 before you compile C.
Range listing
The second program prints every triangular number from 1 through 50 so you can spot the pattern quickly.
Prerequisites
You can follow this page if you have written a few tiny JavaScript programs before.
function,console.log(), and awhileorforloop.- Comfort adding small whole numbers in your head (for example
1 + 2 + 3 + 4 = 10). - Optional later:
Math.sqrt()if you explore square-root shortcuts.
What is a triangular number?
A triangular number is what you get when you add the first k counting numbers: 1 + 2 + 3 + … + k. People call that total Tk (read “T sub k”).
There is a shortcut you may see in textbooks: Tk = k × (k + 1) / 2. You do not have to memorize it to understand the code here—the programs build the same totals by adding step by step in a loop.
Quick examples
- Build-up
- 1 + 2 + 3 = 6, next step 6 + 4 = 10
- Verdict
- You never land exactly on 7.
- Build-up
- Just the first row: 1
- Verdict
- Smallest positive triangular number.
Live preview
This mirrors the first JavaScript program: start at zero, add 1, then 2, then 3, until the running total is at least your target. If it lands exactly on the target, the number is triangular.
Algorithm
Goal: given a positive integer num, return true if num equals 1 + 2 + … + k for some k, and false otherwise.
Reject bad input
If num < 1, return false for this tutorial’s definition (we focus on ordinary counting numbers).
Running total
Set sum = 0 and k = 1.
Add the next row
While sum < num, do sum += k and then k++. Stop when sum reaches or passes num.
Decide
If sum == num, the answer is true. If sum > num, you overshot—the answer is false.
📜 Pseudocode
function isTriangular(num):
if num < 1:
return false
sum ← 0
k ← 1
while sum < num:
sum ← sum + k
k ← k + 1
return sum = numCheck a single number (loop, no math library)
This version only needs plain JavaScript. Change number to try other values.
function isTriangular(num) {
if (num < 1) return false;
let sum = 0;
let k = 1;
while (sum < num) {
sum += k;
k++;
}
return sum === num;
}
const number = 10;
if (isTriangular(number)) {
console.log(number + " is a triangular number.");
} else {
console.log(number + " is not a triangular number.");
}Explanation
For number = 10, the loop adds 1 + 2 + 3 + 4. The total becomes 10, so sum == num and the function returns 1 (true).
while (sum < num) { sum += k; k++; }Core idea. Each pass adds the next row size: first 1, then 2, then 3, and so on. Stop as soon as you reach or pass the target.
return sum === num;Exact hit only. If you overshoot (for example 7 sits between 6 and 10), the totals never match and the function returns 0.
Triangular numbers from 1 to 50
The same test runs inside a for loop so you can see every triangular value in a small window at once.
function isTriangular(num) {
if (num < 1) return false;
let sum = 0;
let k = 1;
while (sum < num) {
sum += k;
k++;
}
return sum === num;
}
const values = [];
for (let i = 1; i <= 50; i++) {
if (isTriangular(i)) values.push(i);
}
console.log("Triangular numbers in the range 1 to 50:");
console.log(values.join(" "));Explanation
for (let i = 1; i <= 50; i++) if (isTriangular(i)) values.push(i);Outer loop. Try every integer in the interval. The helper does the “add 1, then 2, then 3…” work separately for each i.
Notes and optional shortcuts
Formula check. If num equals k(k+1)/2, it is triangular. Solving k(k+1) = 2·num with the quadratic formula leads to this integer test: 8·num + 1 must be a perfect square, and its square root must be odd. Handy in JavaScriptontests; the loop stays easier to narrate in JavaScriptlass.
Square-root trick (uses floats). Let n = Math.floor(Math.sqrt(2 * num)). If n * (n + 1) / 2 === num, then num is triangular. Remember very large integers can stress floating-point rounding.
Range programs. Recomputing isTriangular(i) from scratch for each i is simple. If you ever need huge ranges, you can generate triangular numbers directly with k(k+1)/2 instead of testing every integer.
❓ FAQ
🔄 Input / output examples
Example 1 uses a fixed number. Change it directly or parse input from a form/CLI for interactive runs.
Input number | Typical line (Example 1) |
|---|---|
| 10 | 10 is a triangular number. |
| 7 | 7 is not a triangular number. |
| 1 | 1 is a triangular number. |
| 6 | 6 is a triangular number. |
For Example 2 with bounds 1 and 50, the printed list is:
Triangular numbers in the range 1 to 50:
1 3 6 10 15 21 28 36 45 Edge cases
Small details that keep homework answers tidy.
num < 1Non-positive values
This page treats triangular numbers on 1, 2, 3, …. Return false (or handle separately) if someone passes zero or negatives. (Some books also define T0 = 0; say that aloud if your teacher uses it.)
Stopping at the right moment
The loop must stop when sum ≥ num. If you only checked sum == num inside the loop without ever allowing sum > num, you could spin forever on a non-triangular value.
Big totals
For very large inputs, sum or k * (k + 1) / 2 can overflow a 32-bit int. Widen to long long if the problem allows huge numbers.
⏱️ Time and space complexity
| Approach | Time (single num) | Extra space |
|---|---|---|
| Additive loop (this page) | O(√num) iterations in the worst case | O(1) |
Closed form k(k+1)/2 or discriminant trick | O(1) arithmetic | O(1) |
Print all triangular in [1, U] with per-value test | roughly O(U3/2) | O(1) |
Only a handful of integers live in memory; aside from the call stack, extra space is constant.
Summary
- Idea: triangular numbers are the totals
1,1+2,1+2+3,1+2+3+4, and so on. - Code: keep a running sum, add the next integer each time, stop when you reach or pass the target, then check for an exact match.
- Extra:
Tk = k(k+1)/2and the8n+1square test are fast shortcuts once the story above makes sense.
The nth triangular number counts how many balls you need to make a tight triangle with n rows: 1 in the top row, 2 in the next, then 3, and so on. The sequence starts 1, 3, 6, 10, 15, 21… and shows up in handshakes, bowling pins, and simple loop puzzles.
9 people found this page helpful
