# Finding a "Perfect Number"

Page 1 of 1

## 2 Replies - 3220 Views - Last Post: 13 September 2010 - 11:54 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=190223&amp;s=5d870356033a412392e22ff6fc57d35f&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 Johnny Feelgood

Reputation: 0
• Posts: 2
• Joined: 13-September 10

# Finding a "Perfect Number"

Posted 13 September 2010 - 10:44 AM

Hi,

I'm a beginner self-taught Java programmer working my way through the Deitel & Deitel examples. I'm on the methods chapter, and it's asking me to come up with a formula to find any perfect numbers between 1 and 1000(sum of factors = number). The problem is it identifies the perfect numbers (6,28...) correctly but gives me others as well (24 for example). Here's the code:

```package random;

public class PerfectNumber {

public void numbers() {
for (int i = 1; i < 1000; i++) {
int num = i;

isPerfect(num);
}
}

public void isPerfect(int num) {
int total = 0;
for (int i = 1; i < num; i++) {
if (num % i == 0) {
total += i;

if (total == num) {
System.out.println(num + "");
}
}
}

}

public static void main(String[] args) {
PerfectNumber pn = new PerfectNumber();
pn.numbers();
}

}

```

With the results:
6 24 28 496

What am I doing wrong?

Is This A Good Question/Topic? 0

## Replies To: Finding a "Perfect Number"

Reputation: 32
• Posts: 135
• Joined: 21-August 10

## Re: Finding a "Perfect Number"

Posted 13 September 2010 - 11:12 AM

I think your problem is here, in that you are checking the total against the number prior to summing up all the divisors of the number

```		for (int i = 1; i < num; i++) {
if (num % i == 0) {
total += i;

if (total == num) {
System.out.println(num + "");
}
}
}

```

For instance, with your example of 24, you are adding the divisors 1 + 2 + 3 + 4 + 6 + 8 and then printing when the total hits 24. However, this would miss the final divisor, 12, and adding that would put the total at 36, which is not a perfect number.

Try putting the test outside the for loop.

This post has been edited by javadork: 13 September 2010 - 11:22 AM

### #3 Johnny Feelgood

Reputation: 0
• Posts: 2
• Joined: 13-September 10

## Re: Finding a "Perfect Number"

Posted 13 September 2010 - 11:54 AM

That was exactly it. Thanks a lot!