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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With