2 Replies - 2490 Views - Last Post: 13 September 2010 - 11:54 AM Rate Topic: -----

#1 Johnny Feelgood  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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"

#2 javadork  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 32
  • View blog
  • 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.

[Edited for additional clarity.]

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

Was This Post Helpful? 1
  • +
  • -

#3 Johnny Feelgood  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1