Find the sequence number of a triangular number
Last Updated :
29 Jan, 2024
Given an integer N print the sequence number of the given Triangular Number. If the number is not a triangular number then print -1.
A number is termed as 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, the second row has two points, the third row has three points and so on.
First 10 triangular number are: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55.

Examples:
Input: N = 21
Output:6
Explanation:
Since 15 is a 6th Triangular Number.
Input: N = 12
Output:-1
Explanation:
Since 12 is not a Triangular Number
Approach:
- Since triangular numbers are the sum of natural numbers so can be generalized as a quadratic equation.
C++
// C++ code to print sequence
// number of a triangular number
#include<bits/stdc++.h>
using namespace std;
int main()
{
int N = 21;
int A = sqrt(2 * N + 0.25) - 0.5;
int B = A;
// If N is not triangular number
if (B != A)
cout << "-1";
else
cout << B;
}
// This code is contributed by yatinagg
Java
// Java code to print sequence
// number of a triangular number
import java.util.*;
class GFG{
public static void main(String args[])
{
int N = 21;
int A = (int)(Math.sqrt(2 * N + 0.25) - 0.5);
int B = A;
// If N is not tringular number
if (B != A)
System.out.print("-1");
else
System.out.print(B);
}
}
// This code is contributed by Akanksha_Rai
Python3
# Python3 code to print sequence
# number of a triangular number
import math
N = 21
A = math.sqrt(2 * N + 0.25)-0.5
B = int(A)
# if N is not tringular number
if B != A:
print(-1)
else:
print(B)
C#
// C# code to print sequence
// number of a triangular number
using System;
class GFG{
public static void Main()
{
int N = 21;
int A = (int)(Math.Sqrt(2 * N + 0.25) - 0.5);
int B = A;
// If N is not tringular number
if (B != A)
Console.Write("-1");
else
Console.Write(B);
}
}
// This code is contributed by Code_Mech
JavaScript
<script>
// javascript code to print sequence
// number of a triangular number
let N = 21;
let A = Math.sqrt(2 * N + 0.25) - 0.5;
let B = A;
// If N is not tringular number
if (B != A)
document.write("-1");
else
document.write(B);
// This code is contributed by Rajput-Ji
</script>
Time Complexity: O(logN) as sqrt function is being used
Auxiliary Space: O(1)
Approach 02 : This approach works because it iterates through the triangular numbers until it either finds the exact match or number greater than N.
C++
#include <iostream>
using namespace std;
// Function to find the row number of triangular number
int GFG(int N) {
int triangular = 8;
int n = 1;
// The Loop until the current triangular number is less than N
while (triangular < N) {
triangular += n;
n++;
}
// Check if the calculated triangular number matches N
if (triangular == N) {
return n - 1;
} else {
return -1;
}
}
int main() {
int N;
cin >> N;
// Call the function to find the triangular row
int result = GFG(N);
// Output the result
if (result != -1) {
cout << "Output: " << result << endl;
// If N is a triangular number
} else {
cout << "Output: -1" << endl;
// If N is not a triangular number
}
return 0;
}
Java
import java.util.Scanner;
public class GFG {
// Function to find the triangular row
static int findTriangularRow(int N) {
int triangular = 8;
int n = 1;
// Loop until the current triangular number is less than N
while (triangular < N) {
triangular += n;
n++;
}
// Check if the calculated triangular number matches N
if (triangular == N) {
return n - 1;
} else {
return -1;
}
}
public static void main(String[] args) {
// Input the value of N
int N = 12;
// Call the function to find the triangular row
int result = findTriangularRow(N);
// Output the result
if (result != -1) {
System.out.println("Output: " + result);
// If N is a triangular number
} else {
System.out.println("Output: -1");
// If N is not a triangular number
}
}
}
Python3
def GFG(N):
triangular = 8
n = 1
# Loop until the current triangular number is less than N
while triangular < N:
triangular += n
n += 1
# Check if the calculated triangular number matches N
if triangular == N:
return n - 1
else:
return -1
def main():
# Input the value of N
N = 12
# Call the function to find the triangular row
result = GFG(N)
# Output the result
if result != -1:
print("Output:", result)
# If N is a triangular number
else:
print("Output: -1")
# If N is not a triangular number
if __name__ == "__main__":
main()
C#
using System;
class MainClass
{
// Function to find the row number of triangular number
static int GFG(int N)
{
int triangular = 8;
int n = 1;
// Loop until the current triangular number is less than N
while (triangular < N)
{
triangular += n;
n++;
}
// Check if the calculated triangular number matches N
if (triangular == N)
{
return n - 1;
}
else
{
return -1;
}
}
public static void Main(string[] args)
{
int N;
// Input N from the user
Console.Write("Enter N: ");
N = Convert.ToInt32(Console.ReadLine());
// Call the function to find the triangular row
int result = GFG(N);
// Output the result
if (result != -1)
{
Console.WriteLine($"Output: {result}");
// If N is a triangular number
}
else
{
Console.WriteLine("Output: -1");
// If N is not a triangular number
}
}
}
JavaScript
// Function to find the row number of a triangular number
function findTriangularRow(N) {
let triangular = 8;
let n = 1;
// Loop until the current triangular number is less than N
while (triangular < N) {
triangular += n;
n++;
}
// Check if the calculated triangular number matches N
if (triangular === N) {
return n - 1;
} else {
return -1;
}
}
// Input N from the user
let N = parseInt(prompt("Enter N:"));
// Call the function to find the triangular row
let result = findTriangularRow(N);
// Output the result
if (result !== -1) {
console.log(`Output: ${result}`);
// If N is a triangular number
} else {
console.log("Output: -1");
// If N is not a triangular number
}
Time complexity: O(sqrt(N))
Auxiliary space complexity: O(1)
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read