- Build-up
- 1 + 2 + 3 + 4 = 10
- Verdict
- Fourth triangular number (four rows).
Check Triangular Number in Python
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, andprint().- 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
- 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 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.
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
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 Check a single number (loop, beginner-friendly)
This version is pure Python. Change number in the script (or use input()) to test different values.
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 += 1Core 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 == numExact hit only. If you overshoot (for example 7 sits between 6 and 10), the totals never match and the function returns False.
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.
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
🔄 Input / output examples
Example 1 uses a fixed number. Change it or read with int(input()) 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; mention this if your class uses it.)
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.
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
| Approach | Time (single num) | Extra space |
|---|---|---|
| Additive loop (this page) | O(sqrt(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(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)/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
