Results 1 to 3 of 3
Thread: java question
- 04-12-2012, 02:02 AM #1Member
- Join Date
- Apr 2012
- Rep Power
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?
public class test
public static void main(String args)
// Declare and initialize variables here.
int zero = 0;
int i = 1;
int sum = 0;
nString = JOptionPane.showInputDialog("Input n: ");
n = Integer.parseInt(nString);
while (i < n/2)
if (zero == n / i)
if (sum == n)
System.out.println(n + " is a perfect number");
System.out.println(n + " is not a perfect number");
- 04-12-2012, 02:37 AM #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#codeIf you don't understand my response, don't ignore it, ask a question.
- 04-12-2012, 05:23 AM #3
Re: java question
In addition to what Norm said, please use a meaningful subject line. "java question" isn't one.
dbIf you're forever cleaning cobwebs, it's time to get rid of the spiders.
- By joker760 in forum New To JavaReplies: 3Last Post: 12-13-2011, 05:01 PM
- By joe98 in forum New To JavaReplies: 3Last Post: 03-29-2011, 11:09 AM
- By joe98 in forum New To JavaReplies: 7Last Post: 03-23-2011, 08:09 AM
- By hakimade in forum Advanced JavaReplies: 1Last Post: 07-01-2009, 08:15 AM
- By Jay-1.1 in forum New To JavaReplies: 11Last Post: 05-01-2008, 05:04 PM