Fastest method to define whether a number is a triangular number

后端 未结 8 985
失恋的感觉
失恋的感觉 2020-12-14 12:18

A triangular number is the sum of the n natural numbers from 1 to n. What is the fastest method to find whether a given positive integer number is a triangular one?

He

8条回答
  •  忘掉有多难
    2020-12-14 12:43

    We just need to check if 8*(your integer to be checked)+1 is a perfect square or not!

    public Boolean isSquare(int x)
    {
        return(Math.sqrt(x)==(int)Math.sqrt(x));    // x will be a perfect square if and only if it's square root is an Integer.
    }
    
    }
    public Boolean isTriangular(int z)
    {
        return(isSquare(8*z+1));
    }
    

提交回复
热议问题