Open In App

Find the sequence number of a triangular number

Last Updated : 29 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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: 

  1. 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>


Output

6

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
}


Output

Output: -1

Time complexity: O(sqrt(N))

Auxiliary space complexity: O(1)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads