1. Member Join Date
Apr 2012
Posts
1
Rep Power
0

## java question

Hello,

I am trying to write code to get a perfect number. here is the definition of a perfect number:

A positive integer is called perfect if it is the sum of its positive proper divisors. Thus, to find proper divisors of a number n, we must try all values of m between 1 and n /2. For example, the positive proper divisors of 6 are 1, 2, and 3 and 1 + 2 + 3 = 6. Therefore, 6 is perfect. 28 is also perfect (1,2,4,7,14=28)

With my code, I keep getting not perfect for any number I enter. Any ideas what I have wrong?

import javax.swing.*;
public class test
{
public static void main(String args[])
{
// Declare and initialize variables here.

int n;
String nString;
int zero = 0;
int i = 1;
int sum = 0;
int sumInt;

nString = JOptionPane.showInputDialog("Input n: ");
n = Integer.parseInt(nString);
while (i < n/2)
{
if (zero == n / i)
{
sumInt=sum+i;
i++;
sumInt=sum;
}
else
{i++;
}
}
if (sum == n)
System.out.println(n + " is a perfect number");
else
System.out.println(n + " is not a perfect number");
System.exit(0);
}
}  Reply With Quote

2. ## Re: java question

Try debugging the code by adding printlns to show all your intermediate results as the loop goes around.
The output should should you where your logic is going wrong.

Please edit the code an add the proper indentations and formatting to make the code more readable.
Also put the code in code tags to preserve the formatting.
http://www.java-forums.org/misc.php?do=bbcode#code  Reply With Quote

3. ## Re: java question

In addition to what Norm said, please use a meaningful subject line. "java question" isn't one.

db  Reply With Quote

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•