Check Triangular Number in Python

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 Python 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 Python 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 external library is required.

Live preview

Watch the running total grow step by step for values like 6, 10, or 7.

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 Python programs before.

  • def, if, while/for, and print().
  • Comfort adding small whole numbers in your head (for example 1 + 2 + 3 + 4 = 10).
  • Optional later: math shortcuts like k * (k + 1) // 2, after understanding the loop first.

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 Python 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 total = 0 and k = 1.

Add the next row

While total < num, do total += k and then k += 1. Stop when total reaches or passes num.

Decide

If total == num, the answer is true. If total > num, you overshot - the answer is false.

📜 Pseudocode

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

Check a single number (loop, beginner-friendly)

This version is pure Python. Change number in the script (or use input()) to test different values.

python
def is_triangular(num: int) -> bool:
    if num < 1:
        return False

    total = 0
    k = 1

    while total < num:
        total += k
        k += 1

    return total == num


number = 10

if is_triangular(number):
    print(f"{number} is a triangular number.")
else:
    print(f"{number} is not a triangular number.")

Explanation

For number = 10, the loop adds 1 + 2 + 3 + 4. The total becomes 10, so total == num and the function returns True.

while total < num: total += k; k += 1

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 total == num

Exact hit only. If you overshoot (for example 7 sits between 6 and 10), the totals never match and the function returns False.

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 at once.

python
def is_triangular(num: int) -> bool:
    if num < 1:
        return False

    total = 0
    k = 1

    while total < num:
        total += k
        k += 1

    return total == num


print("Triangular numbers in the range 1 to 50:")
for i in range(1, 51):
    if is_triangular(i):
        print(i, end=" ")
print()

Explanation

for i in range(1, 51): if is_triangular(i): print(i, end=" ")

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 contests; the loop stays easier to narrate in class.

Square-root trick. You can use math.isqrt(8 * num + 1) for integer-safe checks in Python without floating-point rounding issues.

Range programs. Recomputing is_triangular(i) from scratch for each i is simple. If you need huge ranges, generate triangular numbers directly with k * (k + 1) // 2.

❓ 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, ...) 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 square root checks, but the beginner loop needs no imports.

🔄 Input / output examples

Example 1 uses a fixed number. Change it or read with int(input()) 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; mention this if your class uses it.)

Overshoot

Stopping at the right moment

The loop must stop when total >= num. If you only checked equality inside the loop without allowing overshoot, you can run forever on a non-triangular value.

Types

Big totals

Python integers are arbitrary precision, so overflow is not the same problem as in C. But very large values can still take more loop steps.

⏱️ Time and space complexity

ApproachTime (single num)Extra space
Additive loop (this page)O(sqrt(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(U^(3/2))O(1)

Only a handful of integers live in memory; aside from function frames, 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 total, 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