V. Srikanth
Posts: 9
Nickname: iamnobody
Registered: Dec, 2002
|
|
Re: Novice Java question
|
Posted: Dec 23, 2002 11:19 PM
|
|
Hi Joyce,
Yes, I can create a method to find it out.
We knew that quad. eqn was : n*n + n - 2 *t = 0 => For finding roots, a = 1, b = 1, c = 2*t => Roots r1 = (sqrt(1+8*t) - 1)/2 r2 = (sqrt(1+8*t) + 1)/2
With this we can go ahead with the program. Following is the working program:
// Finds if a given number is a triangle number or not.
import java.io.*;
public class TriangularNumber {
public static void main(String[] s) throws IOException {
BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter a number : " );
int n = Integer.parseInt(stdIn.readLine());
if (checkTriangular(n))
System.out.println(n + " is a triangular number.");
else
System.out.println(n + " is not a triangular number.");
}
public static boolean checkTriangular(int num) {
float r1 = 0, r2 = 0;
float det = 0;
det = (float)Math.sqrt(1 + 8 * num);
if (det < 0) // Imaginary roots, => not Triangle #
return false;
r1 = (det - 1) / 2;
r2 = (det + 1) / 2;
if (r1 > 0) {
if (r1 == (int)r1)
return true; // Triangle #
}
if (r2 > 0) {
if (r2 == (int)r2)
return true; // Triangle #
}
return false; // not Triangle #
}
}
Now show me the money :-)))))
|
|