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
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));
}
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.
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.
An integer x is triangular exactly if 8x + 1 is a square.
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 ...
int tri=(8*number)+1;// you can remove this for checking the perfect square and remaining all same for finding perfect square
double trinum=Math.sqrt(tri);
int triround=(int) Math.ceil(trinum);
if((triround*triround)==tri)
{
System.out.println("Triangular");
}
else
{
System.out.println("Not Triangular");
}
Here ceil will always look at next highest number so this will give a perfect chance for verification.