Triangular Number in java

Triangular Number in java

Given a number N. Check whether it is a triangular number or not.

Note: 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.
The starting triangular numbers are 1, 3 (1+2), 6 (1+2+3), 10 (1+2+3+4).

Example 1:

Input: N=55 Output: 1 Explanation: 55 is a triangular number. It can be represented in 10 rows.

Example 2:

Input: N=56 Output: 0 Explanation: 56 is not a triangular number.

Your Task:
You need to take a number N as input parameter and returns 1 if it is a triangular number. Otherwise, it returns 0.


Solution of Triangular Number in java:–

import java.util.*;
public class Main {
    public static boolean isTriangular(int n){
      int l = 0, r = 15;
      while( l <= r)
          int mid = (l + r)/2;
          int result = mid * (mid + 1) / 2;
          if(result == n)
            return true;
          if(result < n)
            l = mid + 1;
            r = mid - 1;
      return false;
    public static void main(String args[]) {
        Scanner input = new Scanner(;
        int n = input.nextInt();

Add a Comment

Your email address will not be published. Required fields are marked *