Check Triangular Number in JavaScript

Beginner
⏱️ 11 min read
📚 Updated: May 2026
🎯 2 Code Examples
Number theory

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 a while or for loop.
  • 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

10 Triangular
Build-up
1 + 2 + 3 + 4 = 10
Verdict
Fourth triangular number (four rows).
7 Not triangular
Build-up
1 + 2 + 3 = 6, next step 6 + 4 = 10
Verdict
You never land exactly on 7.
1 Triangular
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.

Use whole numbers n ≥ 1. Very large values are capped so the tab stays responsive.

Live result
Press “Run check” to see the running total and the verdict.

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

Pseudocode
function isTriangular(num):
    if num < 1:
        return false
    sum ← 0
    k ← 1
    while sum < num:
        sum ← sum + k
        k ← k + 1
    return sum = num
1

Check a single number (loop, no math library)

This version only needs plain JavaScript. Change number to try other values.

JavaScript
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.");
}
Try it Yourself

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.

2

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.

JavaScript
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(" "));
Try it Yourself

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

Start at 1, then add 2, then add 3, then add 4, and keep going. Every total you hit along the way (1, 3, 6, 10, 15, &hellip;) is a triangular number. It is the same as stacking rows of dots: 1 dot, then 2, then 3, and counting all dots.
Because 1 + 2 + 3 + 4 = 10. That is the fourth triangular number. You can picture four rows of objects with lengths 1, 2, 3, and 4.
If the bottom row has k objects, the total count is the sum 1+2+&hellip;+k. That sum always simplifies to k times (k+1), divided by 2. It is a shortcut; the programs on this page can use a loop instead if you prefer to see each step.
Yes. The first triangular number is just the single row &ldquo;1&rdquo; by itself.
Not the same object. Pascal&rsquo;s triangle is a bigger table of numbers. Triangular numbers are one simple sequence you get by adding 1, then 2, then 3, and so on.
No for the loop versions on this page. Optional shortcuts use <code>Math.sqrt()</code> if you want a formula-based check.

🔄 Input / output examples

Example 1 uses a fixed number. Change it directly or parse input from a form/CLI for interactive runs.

Input numberTypical line (Example 1)
1010 is a triangular number.
77 is not a triangular number.
11 is a triangular number.
66 is a triangular number.

For Example 2 with bounds 1 and 50, the printed list is:

Console
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 < 1

Non-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.)

Overshoot

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.

Types

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

ApproachTime (single num)Extra space
Additive loop (this page)O(√num) iterations in the worst caseO(1)
Closed form k(k+1)/2 or discriminant trickO(1) arithmeticO(1)
Print all triangular in [1, U] with per-value testroughly 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)/2 and the 8n+1 square test are fast shortcuts once the story above makes sense.
Did you know?

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful