A number is termed a triangular number if we can represent it in the form of a triangular grid of points such that the points form an equilateral triangle and each row contains as many points as the row number, i.e., the first row has one point, second row has two points, third row has three points and so on. The starting triangular numbers are 1, 3 (1+2), 6 (1+2+3), 10 (1+2+3+4).

How to check if a number is Triangular?
The idea is based on the fact that n'th triangular number can be written as sum of n natural numbers, that is n*(n+1)/2. The reason for this is simple, base line of triangular grid has n dots, line above base has (n-1) dots and so on.
Examples:
Input: 10
Output: True
Explanation: 10
is a triangular number because it can be written as the sum of the first 4 natural numbers: 1 + 2 + 3 + 4 = 10
.
Input: 8
Output: False
Explanation: 8
is not a triangular number because no sum of the first n
natural numbers equals 8
. The closest triangular numbers are 6 (1+2+3)
and 10 (1+2+3+4)
.
[Naive Approach] Iterative Summation Method - O(n) time and O(1) space
We start with 1 and check if the number is equal to 1. If it is not, we add 2 to make it 3 and recheck with the number. We repeat this procedure until the sum remains less than or equal to the number that is to be checked for being triangular.
Following is the implementations to check if a number is triangular number.
Below is the implementation of above approach
C++
// C++ program to check if a number is a triangular number
// using simple approach.
#include <iostream>
using namespace std;
// Returns true if 'num' is triangular, else false
bool isTriangular(int num)
{
// Base case
if (num < 0)
return false;
// A Triangular number must be sum of first n
// natural numbers
int sum = 0;
for (int n=1; sum<=num; n++)
{
sum = sum + n;
if (sum==num)
return true;
}
return false;
}
// Driver code
int main()
{
int n = 55;
if (isTriangular(n))
cout << "The number is a triangular number";
else
cout << "The number is NOT a triangular number";
return 0;
}
Java
// Java program to check if a
// number is a triangular number
// using simple approach
class GFG
{
// Returns true if 'num' is
// triangular, else false
static boolean isTriangular(int num)
{
// Base case
if (num < 0)
return false;
// A Triangular number must be
// sum of first n natural numbers
int sum = 0;
for (int n = 1; sum <= num; n++)
{
sum = sum + n;
if (sum == num)
return true;
}
return false;
}
// Driver code
public static void main (String[] args)
{
int n = 55;
if (isTriangular(n))
System.out.print("The number "
+ "is a triangular number");
else
System.out.print("The number"
+ " is NOT a triangular number");
}
}
// This code is contributed
// by Anant Agarwal.
Python
# Python3 program to check if a number is a
# triangular number using simple approach.
# Returns True if 'num' is triangular, else False
def isTriangular(num):
# Base case
if (num < 0):
return False
# A Triangular number must be
# sum of first n natural numbers
sum, n = 0, 1
while(sum <= num):
sum = sum + n
if (sum == num):
return True
n += 1
return False
# Driver code
n = 55
if (isTriangular(n)):
print("The number is a triangular number")
else:
print("The number is NOT a triangular number")
# This code is contributed by Smitha Dinesh Semwal.
C#
// C# program to check if a number is a
// triangular number using simple approach
using System;
class GFG {
// Returns true if 'num' is
// triangular, else false
static bool isTriangular(int num)
{
// Base case
if (num < 0)
return false;
// A Triangular number must be
// sum of first n natural numbers
int sum = 0;
for (int n = 1; sum <= num; n++)
{
sum = sum + n;
if (sum == num)
return true;
}
return false;
}
// Driver code
public static void Main ()
{
int n = 55;
if (isTriangular(n))
Console.WriteLine("The number "
+ "is a triangular number");
else
Console.WriteLine("The number"
+ " is NOT a triangular number");
}
}
// This code is contributed by vt_m.
JavaScript
<script>
// javascript program to check if a number is a triangular number
// using simple approach.
// Returns true if 'num' is triangular, else false
function isTriangular(num)
{
// Base case
if (num < 0)
return false;
// A Triangular number must be sum of first n
// natural numbers
let sum = 0;
for (let n = 1; sum <= num; n++)
{
sum = sum + n;
if (sum == num)
return true;
}
return false;
}
// Driver code
let n = 55;
if (isTriangular(n))
document.write( "The number is a triangular number");
else
document.write( "The number is NOT a triangular number");
// This code is contributed by aashish1995
</script>
PHP
<?php
// PHP program to check if a number is a
// triangular number using simple approach.
// Returns true if 'num' is triangular,
// else false
function isTriangular( $num)
{
// Base case
if ($num < 0)
return false;
// A Triangular number must be
// sum of first n natural numbers
$sum = 0;
for ($n = 1; $sum <= $num; $n++)
{
$sum = $sum + $n;
if ($sum == $num)
return true;
}
return false;
}
// Driver code
$n = 55;
if (isTriangular($n))
echo "The number is a triangular number";
else
echo "The number is NOT a triangular number";
// This code is contributed by Rajput-Ji
?>
OutputThe number is a triangular number
[Expected Approach] Quadratic Equation Root Formula Method - O(log n) time and O(1) Space
We form a quadratic equation by equating the number to the formula of sum of first 'n' natural numbers, and if we get atleast one value of 'n' that is a natural number, we say that the number is a triangular number.
Let the input number be 'num'. We consider,
(n*(n+1))/2 = num
as,
n2 + n + (-2 * num) = 0
Below is the implementation of above approach.
C++
// C++ program to check if a number is a triangular number
// using quadratic equation.
#include <bits/stdc++.h>
using namespace std;
// Returns true if num is triangular
bool isTriangular(int num)
{
if (num < 0)
return false;
// Considering the equation n*(n+1)/2 = num
// The equation is : a(n^2) + bn + c = 0";
int c = (-2 * num);
int b = 1, a = 1;
int d = (b * b) - (4 * a * c);
if (d < 0)
return false;
// Find roots of equation
float root1 = ( -b + sqrt(d)) / (2 * a);
float root2 = ( -b - sqrt(d)) / (2 * a);
// checking if root1 is natural
if (root1 > 0 && floor(root1) == root1)
return true;
// checking if root2 is natural
if (root2 > 0 && floor(root2) == root2)
return true;
return false;
}
// Driver code
int main()
{
int num = 55;
if (isTriangular(num))
cout << "The number is a triangular number";
else
cout << "The number is NOT a triangular number";
return 0;
}
Java
// Java program to check if a number is a
// triangular number using quadratic equation.
import java.io.*;
class GFG {
// Returns true if num is triangular
static boolean isTriangular(int num)
{
if (num < 0)
return false;
// Considering the equation
// n*(n+1)/2 = num
// The equation is :
// a(n^2) + bn + c = 0";
int c = (-2 * num);
int b = 1, a = 1;
int d = (b * b) - (4 * a * c);
if (d < 0)
return false;
// Find roots of equation
float root1 = ( -b +
(float)Math.sqrt(d)) / (2 * a);
float root2 = ( -b -
(float)Math.sqrt(d)) / (2 * a);
// checking if root1 is natural
if (root1 > 0 && Math.floor(root1)
== root1)
return true;
// checking if root2 is natural
if (root2 > 0 && Math.floor(root2)
== root2)
return true;
return false;
}
// Driver code
public static void main (String[] args) {
int num = 55;
if (isTriangular(num))
System.out.println("The number is"
+ " a triangular number");
else
System.out.println ("The number "
+ "is NOT a triangular number");
}
}
//This code is contributed by vt_m.
Python
# Python3 program to check if a number is a
# triangular number using quadratic equation.
import math
# Returns True if num is triangular
def isTriangular(num):
if (num < 0):
return False
# Considering the equation n*(n+1)/2 = num
# The equation is : a(n^2) + bn + c = 0
c = (-2 * num)
b, a = 1, 1
d = (b * b) - (4 * a * c)
if (d < 0):
return False
# Find roots of equation
root1 = ( -b + math.sqrt(d)) / (2 * a)
root2 = ( -b - math.sqrt(d)) / (2 * a)
# checking if root1 is natural
if (root1 > 0 and math.floor(root1) == root1):
return True
# checking if root2 is natural
if (root2 > 0 and math.floor(root2) == root2):
return True
return False
# Driver code
n = 55
if (isTriangular(n)):
print("The number is a triangular number")
else:
print("The number is NOT a triangular number")
# This code is contributed by Smitha Dinesh Semwal
C#
// C# program to check if a number is a triangular
// number using quadratic equation.
using System;
class GFG {
// Returns true if num is triangular
static bool isTriangular(int num)
{
if (num < 0)
return false;
// Considering the equation n*(n+1)/2 = num
// The equation is : a(n^2) + bn + c = 0";
int c = (-2 * num);
int b = 1, a = 1;
int d = (b * b) - (4 * a * c);
if (d < 0)
return false;
// Find roots of equation
float root1 = ( -b + (float)Math.Sqrt(d))
/ (2 * a);
float root2 = ( -b - (float)Math.Sqrt(d))
/ (2 * a);
// checking if root1 is natural
if (root1 > 0 && Math.Floor(root1) == root1)
return true;
// checking if root2 is natural
if (root2 > 0 && Math.Floor(root2) == root2)
return true;
return false;
}
// Driver code
public static void Main () {
int num = 55;
if (isTriangular(num))
Console.WriteLine("The number is a "
+ "triangular number");
else
Console.WriteLine ("The number is NOT "
+ "a triangular number");
}
}
//This code is contributed by vt_m.
JavaScript
<script>
// javascript program to check if a number is a
// triangular number using quadratic equation.
// Returns true if num is triangular
function isTriangular(num)
{
if (num < 0)
return false;
// Considering the equation
// n*(n+1)/2 = num
// The equation is :
// a(n^2) + bn + c = 0";
var c = (-2 * num);
var b = 1, a = 1;
var d = (b * b) - (4 * a * c);
if (d < 0)
return false;
// Find roots of equation
var root1 = (-b + Math.sqrt(d)) / (2 * a);
var root2 = (-b - Math.sqrt(d)) / (2 * a);
// checking if root1 is natural
if (root1 > 0 && Math.floor(root1) == root1)
return true;
// checking if root2 is natural
if (root2 > 0 && Math.floor(root2) == root2)
return true;
return false;
}
// Driver code
var num = 55;
if (isTriangular(num))
document.write("The number is" + " a triangular number");
else
document.write("The number " + "is NOT a triangular number");
// This code is contributed by Rajput-Ji
</script>
PHP
<?php
// PHP program to check if a number is a
// triangular number using quadratic equation.
// Returns true if num is triangular
function isTriangular($num)
{
if ($num < 0)
return false;
// Considering the equation
// n*(n+1)/2 = num
// The equation is :
// a(n^2) + bn + c = 0";
$c = (-2 * $num);
$b = 1; $a = 1;
$d = ($b * $b) - (4 * $a * $c);
if ($d < 0)
return false;
// Find roots of equation
$root1 = (-$b + (float)sqrt($d)) / (2 * $a);
$root2 = (-$b - (float)sqrt($d)) / (2 * $a);
// checking if root1 is natural
if ($root1 > 0 && floor($root1) == $root1)
return true;
// checking if root2 is natural
if ($root2 > 0 && floor($root2) == $root2)
return true;
return false;
}
// Driver code
$num = 55;
if (isTriangular($num))
echo("The number is" .
" a triangular number");
else
echo ("The number " .
"is NOT a triangular number");
// This code is contributed
// by Code_Mech.
?>
OutputThe number is a triangular number
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem