Check Triangular Number in JavaScript

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Number Theory

What You’ll Learn

A triangular number is the total of stacked rows: 1 + 2 + 3 + ... + k, also written Tk = k(k+1)/2. Examples: 1, 3, 6, 10, 15. Non-example: 7 (between 6 and 10). This tutorial covers an additive loop check, a live preview, worked JavaScript examples, edge cases, and complexity.

Add Rows

1+2+3+…

Each total after a full row is triangular.

Exact Hit

total == n

Overshooting means not triangular.

Tk Formula

k(k+1)/2

Closed form for the same sum.

1 Is Yes

First T1

A single-dot triangle counts.

Live Preview

Try 10 / 7

Watch the running total grow.

1..50 List

1 3 6 … 45

See the sequence at a glance.

Introduction

A triangular number is the total after stacking rows of size 1, then 2, then 3, and so on. So 10 = 1+2+3+4 is triangular, while 7 is not — it falls between T3 = 6 and T4 = 10.

Interviews love the additive loop because you can narrate each row. The closed form Tk = k(k+1)/2 (and the related 8n+1 perfect-square test) are useful shortcuts once the idea is clear.

Why it matters?

It connects geometry (stacked rows) to loops and formulas — a friendly number-theory warm-up after basics like swap.

Key Highlights

Row Sums

1 + 2 + … + k

Additive Loop

Stop at or past n.

Formula

k(k+1)/2

vs Pronic

Twice a triangular.

In short: add 1, then 2, then 3… until you hit n exactly or pass it.

📝 Problem & Approach

Given a positive integer n, decide whether it equals 1+2+…+k for some k >= 1.

JavaScript
// 10 -> 1+2+3+4 = 10   triangular
// 7  -> between 6 and 10  not triangular
// 1  -> 1                triangular
// 6  -> 1+2+3 = 6        triangular

Inputs & Outputs

ItemTypeDescription
numnumberValue to test (n >= 1 on this page).
Returnbooleantrue when some k has T_k = num.
total / knumberRunning sum and next row size.

Minimal workflow

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

Method comparison

MethodIdeaNotes
Additive looptotal += k until >= nInterview / classroom default
Generateconsole.log(Math.floor(k*(k+1)/2))Best for listing the sequence
8n+1 squareMath.sqrt(8*n+1) is odd integerFast contest shortcut

⚡ Quick Reference

GoalPattern
Reject non-positiveif (num < 1) return false
Add next rowtotal += k; k += 1
Stopwhile (total < num)
Verdictreturn total === num
Closed formMath.floor(k * (k + 1) / 2)
Fast check8*num + 1 is an odd perfect square

📋 Loop vs Generate vs Formula

Same sequence — different packaging.

Additive
total += k

Clearest check for one n

Generate
Math.floor(k*(k+1)/2)

Build the sequence directly

8n+1
Math.sqrt

Contest shortcut

vs pronic
2 * T_k

Pronic = twice triangular

Context

When This Problem Shows Up

Reach for a triangular check when row-sums or handshake-style totals appear.

  1. Interview warm-ups

    Loop + exact-match narrative.

  2. Sequence listing

    Print T_k values in a band.

  3. Geometry intuition

    Bowling pins, stacked dots.

  4. Handshake / pairs

    n people → T_(n-1) handshakes.

  5. Not Pascal’s triangle

    Different object; related name only.

Key benefit: one picture — stacked rows — that maps cleanly to a short loop and a closed formula.

🔮 Live Preview

Adds 1, then 2, then 3… until the running total reaches or passes your target.

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.

Examples Gallery

Three complete JavaScript programs — check 10, list triangular numbers from 1 to 50, and generate with the closed formula. Click View Output to reveal sample console results.

📚 Getting Started

A pure additive loop with no extras.

Example 1 — Check a Single Number

Beginner-friendly loop. Change number to test other values.

JavaScript
function isTriangular(num) {
  if (num < 1) {
    return false;
  }

  let total = 0;
  let k = 1;

  while (total < num) {
    total += k;
    k += 1;
  }

  return total === num;
}

const number = 10;

if (isTriangular(number)) {
  console.log(`${number} is a triangular number.`);
} else {
  console.log(`${number} is not a triangular number.`);
}

How It Works

For 10 the loop adds 1 + 2 + 3 + 4. The total lands exactly on 10, so the function returns true.

⚡ Hunting in a Range

Reuse the helper to list nearby triangular values.

Example 2 — Triangular Numbers from 1 to 50

The same test runs inside a loop so you can see every triangular value in a small window.

JavaScript
function isTriangular(num) {
  if (num < 1) {
    return false;
  }

  let total = 0;
  let k = 1;

  while (total < num) {
    total += k;
    k += 1;
  }

  return total === num;
}

console.log("Triangular numbers in the range 1 to 50:");
let line = "";
for (let i = 1; i <= 50; i++) {
  if (isTriangular(i)) {
    line += i + " ";
  }
}
console.log(line.trim());

How It Works

Within 1..50 the hits are 1, 3, 6, 10, 15, 21, 28, 36, and 45. Memorizing this short list is a useful interview sanity check.

Example 3 — Generate with the Closed Formula

When you only need the sequence, compute Math.floor(k*(k+1)/2) directly instead of testing every integer.

JavaScript
console.log("Triangular numbers for k = 1 to 9:");
for (let k = 1; k <= 9; k++) {
  const value = Math.floor((k * (k + 1)) / 2);
  console.log(`T_${k} = ${k}*${k + 1}/2 = ${value}`);
}

How It Works

Integer division with Math.floor keeps results exact because k(k+1) is always even. This matches the 1..50 list without scanning every i.

🧠 How the Algorithm Decides

1

Reject num < 1

This page uses positive counting numbers.

Guard
2

Add next row k

total += k; k += 1

Loop
3

Stop when total >= num

Avoid an infinite loop on misses.

Exit
=

Compare total === num

Exact hit means triangular.

🔎 Worked Walkthrough — 10 vs 7

Compare an exact hit with a miss that overshoots.

Addtotalvs 10vs 7
+11<<
+23<<
+36<<
+410= yes> no (passed 7)

10 lands exactly; 7 is skipped between 6 and 10.

Use Cases

Where triangular checks show up beyond the interview prompt.

1. Interview Classics

Additive loop + exact match.

Example: isTriangular(10).

2. Range Listing

Find T_k values in a band.

Example: 1 3 6 … 45.

3. Formula Generation

Build with k(k+1)/2.

Example: Example 3.

4. Handshakes

Pairs among n people.

Example: T_(n-1).

5. Pronic Cousin

Pronic = 2 × triangular.

Example: related FAQ.

6. Next: Abundant Number

Proper divisors sum past the number.

Example: related CTA.

Pro Tip: open with “1+2+…+k” before naming the formula.

Advantages

Why the additive loop works well for beginners and interviews.

  1. 1. Easy to Narrate

    Dry-run 10 as 1+2+3+4 out loud.

  2. 2. No Imports

    Pure arithmetic and a while loop.

  3. 3. Early Exit

    Stop as soon as total passes n.

  4. 4. Formula Upgrade Path

    Same idea as k(k+1)/2 and 8n+1.

Pro Tip: lead with the loop; mention the 8n+1 square test only as an optional optimization.

Usage Tips

Small habits that keep triangular solutions interview-ready.

  1. 1. Guard num < 1

    Return false for this tutorial’s definition.

  2. 2. Stop When Past n

    while (total < num) prevents infinite loops.

  3. 3. Require Exact Equality

    total === num, not just >=.

  4. 4. Generate When Listing

    Use Math.floor(k*(k+1)/2) for long ranges.

  5. 5. Know 1..50 Hits

    1 3 6 10 15 21 28 36 45

Pro Tip: sanity-check 1, 7, 10, and 15 — if those four behave, your logic is solid.

Common Pitfalls

Mistakes that commonly break triangular-number programs.

  1. 1. Infinite Loop on Misses

    Only checking equality inside the loop.

    → Loop while total < num.

  2. 2. Accepting Overshoots

    Returning true when total > num.

    → Require total === num.

  3. 3. Treating 0 as Yes

    Outside this page’s positive definition.

    → Reject num < 1 (unless class defines T_0).

  4. 4. Confusing with Pascal

    Different triangle concept.

    → Clarify: row-sum sequence only.

  5. 5. Float Division in Formula

    Relying on bare / without flooring for k(k+1)/2.

    → Prefer Math.floor(k * (k + 1) / 2) so results stay ints.

Edge Cases

Handle these before claiming the check is complete.

n < 1

Not triangular here

This page uses 1, 2, 3… (some books define T_0 = 0).

n = 1

Yes

Smallest positive triangular number.

n = 7

No

Between 6 and 10.

Overshoot

Must stop

Loop while total < num.

n = 10

Classic yes

1+2+3+4 = 10.

Huge ranges

Generate, don’t scan

Use Math.floor(k*(k+1)/2).

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Closed form. T_k = k(k+1)/2 always.
  • 8n+1 test. n is triangular iff 8n+1 is an odd perfect square.
  • Pronic link. Pronic numbers are twice triangular numbers.
  • Sequence. 1, 3, 6, 10, 15, 21, 28, 36, 45, …

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Prove 10

  • Show 1+2+3+4
  • Confirm true

2. Reject 7

  • Pass between 6 and 10
  • Confirm false

3. List 1..50

  • Reproduce Example 2
  • Expect 1 3 6 … 45

4. Generate

  • Print T_1..T_9
  • Match Example 3

Notes

  • Idea: triangular numbers are the totals 1, 1+2, 1+2+3, 1+2+3+4, and so on.
  • Loop: add k until total >= num, then check equality.
  • Formula: T_k = k(k+1)/2; optional contest test uses 8n+1 as a perfect square.
  • For huge ranges, generate with Math.floor(k*(k+1)/2) instead of calling isTriangular on every i.

Quick Takeaway: n is triangular when some k >= 1 satisfies 1+2+…+k == n.

⏱️ Time and Space Complexity

ApproachTimeExtra space
Additive loopO(sqrt(num))O(1)
Generate first m valuesO(m)O(1)
Scan 1..U with per-value testroughly O(U^(3/2))O(1)

Because T_k grows like k²/2, the additive search stops after about sqrt(2n) steps.

Wrap Up

🎉 Conclusion

A triangular number is the sum of the first k counting numbers. Add rows until you hit n exactly or pass it, remember that 1 is yes and 7 is no, and upgrade to k(k+1)/2 when you need to generate the sequence.

Practice the three examples above, then continue with abundant numbers in the interview series.

1+2+…+k equals n means triangular.

💡 Best Practices

✅ Do

  • Narrate 1+2+…+k
  • Stop when total >= n
  • Require exact equality
  • Treat 1 as triangular
  • Generate with Math.floor for lists

❌ Don’t

  • Loop forever on misses
  • Accept overshoots as yes
  • Confuse with Pascal’s triangle
  • Use float / for T_k
  • Scan huge ranges naively

Key Takeaways

Knowledge Unlocked

Five things to remember about triangular numbers

Classify row-sum totals the interview-friendly way.

5
Core concepts
L 02

Loop

add until

Method
= 03

Exact

hit or miss

Verdict
T 04

Formula

k(k+1)/2

Shortcut
O 05

Cost

O(√n)

Analysis

❓ Frequently Asked Questions

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, ...) 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+...+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 1 by itself.
Not the same object. Pascal'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 can use Math.sqrt checks, but the beginner loop needs no extras.
No. It sits between 6 (T_3) and 10 (T_4).
Pronic numbers are twice triangular numbers: k*(k+1) = 2 * T_k.
Narrate the additive loop first, then mention T_k = k(k+1)/2 or the 8n+1 perfect-square test.
Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the input and Run.

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.

Continue to Abundant Number

Learn how to check whether a number is abundant in JavaScript.

Abundant number tutorial →

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