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
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;
}
To find if the number triangular number use this formula:
const pagesInBook = (num) => Number.isInteger((Math.sqrt(8 * num+1) -1 )/2)