JackDee
JackDee

Reputation: 1

Find Perfect Number from 1-9999. Exercise from The Art and Science of Java

I am trying to find the perfect number by find out all their divisors. If their sum is equal to the number, then print out the the number. But apparently it's not working.

import acm.program.*;

public class PerfectNumber extends ConsoleProgram{
    public void run() {
        for (int n = 1; n < 9999; n++) {                                                                    
            for (int d = 2; d < n - 1; d++) {
                //d is the potential divisor of n, ranging from 2 to n-1,// 
                //not including 1 and n because they must be the divisors.//
            if (isPerfectNumber(n,d)) 
                print(n );
        }
    }
}

//method that determines if n is perfect number.//
    private boolean isPerfectNumber(int n, int d) {
         while (n % d == 0) {
         int spd = 1;
         spd += d;
         if (spd == n) {
         return true;
         } else {   
          return false;
             }
        }
    }
}

Upvotes: 0

Views: 509

Answers (2)

sir_k
sir_k

Reputation: 332

Looking at the code in your case will return false most of the times. I think what you were looking for is a bit wrong. Because d is smaller than n, and n divided by d will always be grater than 0. Also in that loop you never change the value of d.

A solution might be:

     public void run() {
            for (int n = 1; n < 9999; n++) 
{           spd=1;                                                         
                for (int d = 2; d <= n/2; d++) { //no need to go further than n/2
                    //d is the potential divisor of n, ranging from 2 to n-1,// 
                if(n%d==0) spd+=d; //if n divides by d add it to spd.

            }
            if(spd==n) print(n);
        }

Try this and let me know if it works for you.

I find something cool here : http://en.wikipedia.org/wiki/List_of_perfect_numbers. You should the much faster using this formula: 2^(p−1) × (2^p − 1). You can see the formula better on the wikilink.

Upvotes: 1

isnot2bad
isnot2bad

Reputation: 24444

Method isPerfect should probably be something like that:

public static boolean isPerfect(int number) {
    int s = 1;
    int d = number / 2;
    for(int i = 2; i <= d; i++) {
        if (number % i == 0) s += i;
    }
    return s == number;
}

Upvotes: 0

Related Questions