Hi,
I need to do the following...
A positive number P is a triangular number if there exists a number n such that P=1+2+3+…+n. That is, P is the sum of the numbers from 1 to n.
For example, 6 is a triangular number as 6=1+2+3. Also, 28 is a triangular number as 28=1+2+3+4+5+6+7. However, 7 is not a triangular number. The number 20 is also not a triangular number.
Write a program that will prompt for a positive integer. After a number is entered, the program will determine and print if the number is a triangular or not. If it is triangular , also print the range of numbers that the number is the sum of. Your program will continue reading in numbers and processing them until a non-positive number is read in.
Your output should look something like (the spacing need not be exact):
Enter a positive number (<= 0 to quit): 6
The number 6 is triangular. It is the sum from 1 to 3.
Enter a positive number (<= 0 to quit): 1000
The number 1000 is not triangular.
Enter a positive number (<= 0 to quit): 8128
The number 8128 is triangular. It is the sum from 1 to 127.
Enter a positive number (<= 0 to quit): 33550336
The number 33550336 is triangular. It is the sum from 1 to 8191.
Enter a positive number (<= 0 to quit): -1
End of Processing.
So far I got this... Which is for a Perfect Number program. What parameters do I need to change in here so that I can make the above program work?
public class Triangle {
public static void main (String [] args) {
ConsoleReader console = new ConsoleReader (System.in);
int number; //Number to be calculated
int divisors; //To check sum of divisors
int sum; //Sum
int i;
while(true) {
System.out.print("Enter a positive number (<= 0 to quit): ");
number = console.readInt();
System.out.println();
if (number <= 0)
System.exit(0);
sum = 0;
for (i = 1; i < number - 1; i = i + 1) {
if (number % i == 0)
sum = sum + i;
}
divisors = sum;
if (number == divisors)
System.out.println("The value " + number + " is PERFECT");
else
System.out.println("The number " + number + " is NOT PERFECT");
System.out.println();
}
}
}
Thanks in advance!
P.S I've been browsing this site for some time now, and I must say it is the best site on programming out there! Keep up the good work guys!