Fastest method to define whether a number is a triangular number

后端 未结 8 959
失恋的感觉
失恋的感觉 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:50

    The accepted answers takes you to another step of checking if the number is a perfect square. Why not simply do following? It takes same effort as finding a perfect square.

    public final static boolean isTriangularNumber(final long x)
    {
        if (x < 0)
            return false;
    
        final long n = (long) Math.sqrt(2 * x);
        return n * (n + 1) / 2 == x;
    }
    
    0 讨论(0)
  • 2020-12-14 12:54

    To find if the number triangular number use this formula:

    const pagesInBook = (num) => Number.isInteger((Math.sqrt(8 * num+1) -1 )/2)   
    
    0 讨论(0)
提交回复
热议问题