Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test if inputted number is a triangular number

Tags:

java

math

I need to create a program to test if a given number inputted by the user is a triangular number.

I have created a script that just gives the list of all the triangular numbers, but in this program the user needs to enter a number and the program will have to determine whether that number is triangular or not.

like image 830
user2554427 Avatar asked Dec 09 '22 14:12

user2554427


1 Answers

Since the wikipedia article you refer to state that

An integer x is triangular if and only if 8x + 1 is a square

You can of course make the square check a bit faster, but this can solve it:

public static boolean isTriangularNumber(long num) {
     long calc_num = 8*num+1;
     long t = (long) Math.sqrt(calc_num);
     if (t*t==calc_num) {
        return true;
     }
     return false;
}
like image 78
flogvit Avatar answered Dec 11 '22 04:12

flogvit