views:

333

answers:

4

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?

A: 

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 ...

Charles Bretana
+4  A: 

An integer x is triangular exactly if 8x + 1 is a square.

Toader Mihai Claudiu
If you follow the sparky's answer you will reach the test above. The problem right now is how do you check if a number is a square easily :). See interjay's answer for this.
Toader Mihai Claudiu
Your answer rocks! Simple and elegant. Incidentally, it can be easily demonstrated in at least two different ways. #1 is to work it out via solving the quadratic equation. #2 is to substitue n(n+1)/2 for x in your equation and factor.
Sparky
+2  A: 

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.

Sparky
+15  A: 

If n is the mth 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.

interjay
+1 for link on how to determine if number is perfect square.
Moron
@interjay: You also need to mention that if n is triangular, then 8n+1 is a perfect square: i.e x is triangular if and only if 8x+1 is a perfect square. Having it one way is incomplete.
Moron
@Moron: Updated my answer, thanks for the correction.
interjay