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?
Home work ?
Sum of numbers from 1 to N
1 + 2 + 3 + 4 + ... n-1 + n
if you add the first plus last, and then the second plus the second from last, then ...
= (1+n) + (2+n-1) + (3+n-2) + (4+n-3) + ... (n/2 + n/2+1)
= (n=1) + (n+1) + (n+1) + ... (n+1); .... n/2 times
= n(n+1)/2
This should get you started ...
An integer x is triangular exactly if 8x + 1 is a square.
I don't know if this is the fastest, but here is some math that should get you in the right direction...
S = n (n + 1) / 2
2*S = n^2 + n
n^2 + n - 2*S = 0
You now have a quadratic equation.
Solve for n.
If n does not have an fractional bits, you are good to go.
If n
is the m
th triangular number, then n = m*(m+1)/2
. Solving for m
using the quadratic formula:
m = (sqrt(8n+1) - 1) / 2
So n
is triangular if and only if 8n+1
is a perfect square. To quickly determine whether a number is a perfect square, see this question: Fastest way to determine if an integer’s square root is an integer.
Note that if 8n+1 is a perfect square, then the numerator in the above formula will always be even, so there's no need to check that it is divisible by 2.