测试输入的数字是否为三角形数字

use*_*427 4 java math

我需要创建一个程序来测试用户输入的给定数字是否是三角形数字.

我创建了一个脚本,它只给出了所有三角形数字的列表,但在这个程序中,用户需要输入一个数字,程序必须确定该数字是否为三角形.

flo*_*vit 11

自维基百科文章你提到的那个

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

你当然可以更快地进行方形检查,但这可以解决它:

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;
}
Run Code Online (Sandbox Code Playgroud)