Member Avatar for jmartzr1

Hey everyone, I am having trouble on this one practice problem. It is a question that requires another question I already completed to solve this one. The qusetion is "Implement a method allPerfect() that takes an integer parameter end. The method prints every perfect number from 1 to end. Use the method isPerfect() above to check if a number is perfect. " I am confused on how to use isPerfect to check if the number is perfect or not. Any help would be greatly appreciated.

This is my isPerfect code:

import java.util.*;
public class isPerfect
{
    public boolean isPerfect(int num)
    { 
        int count = 0;
        for(int i = 1; i<= num/2 ; i++)
        {
            if(num%i == 0)
            {   
                count +=i;
            }
        }

        if(count == num)
        {
            System.out.println("This is a pefect number");
            return true;
        }
        else
        {
            System.out.println("This is not a perfect number");
            return false;
        }

    }

    public static void main(String[]args)
    {
        isPerfect ip = new isPerfect();
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter an integer value to see if it is perfect or not");
        int number = scan.nextInt();
        System.out.println(ip.isPerfect(number));
    }
}

Recommended Answers

All 10 Replies

your code will be slow for large "end" parameter, as it has to check for every number because of the for() loops.
a faster method will be this :

from the wiki page for perfect numbers , ull get a formula with a variable p that all perfect numbers (48 of them) follow.

now , in ur code , ur allPerfect() class will take in "end" parameter. and this will keep calling the isPerfect method untill the isPerfect method returns a perfect number value bigger than "end".

going to ur isPerfect() class, it will contain an array of 48 p values that ull get from the wiki page. and in each iteration it will use one value from the p array and return the calculated perfect number based on the formula from the wiki page.

thus the code will work like this :

allPerfect() gets end , and calls isPerfect
isPerfect() returns ith perfect number taking the ith p value from p array
if returned number is greater than end , allperfect no longer calls isPerfect(), and the code exits with the required prints etc.

its hard to write math in daniweb , so i couldnt write the formulas directly here.

if you want a more do it myself sort of code , one option is using seive of erasthosenes to find primes upto "end" , then for each prime , check if (2^p) - 1 is prime or not , if it is prime , then use the formula from the wiki page to get ur perfect number following the same print untill returned value bigger than end principle above.

im posting a code for seive of erasthosenes , i modified it a little. the original version is in here

public class PrimeSieve {

    ArrayList<Integer> primeList = new ArrayList<Integer>();

    public PrimeSieve(int N){
        // initially assume all integers are prime
        boolean[] isPrime = new boolean[N + 1];
        for (int i = 2; i <= N; i++) {
            isPrime[i] = true;
        }

        // mark non-primes <= N using Sieve of Eratosthenes
        for (int i = 2; i * i <= N; i++) {

            // if i is prime, then mark multiples of i as nonprime
            // suffices to consider mutiples i, i+1, ..., N/i
            if (isPrime[i]) {
                for (int j = i; i * j <= N; j++) {
                    isPrime[i * j] = false;
                }
            }
        }

        // count primes
        int primes = 0;
        int index = 0 ;
        for (int i = 2; i <= N; i++) {
            if (isPrime[i]) {
                primeList.add(i);
                primes++;
            }
        }
        System.out.println("The number of primes <= " + N + " is " + primes);
    }

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        PrimeSieve ps = new PrimeSieve(N);
        for(Integer prime : ps.primeList){
            System.out.println(" " + prime);
        }


    }
}

ur isPerfect() method will call the primeSeive , passing it the value of "end" , and then will take in the primeList generated. it will then use primeList to find p for which (2^p) - 1 will be prime. and then , print out the perfect number based on the formula.

void allPerfect(int end)
{
  for(int i = 1;i <= end;i++)
  {
    if(isPerfect(i))
    System.out.print(i+"\n");
  }
}

Thats what the isPerfect() implementation will look like , since you only print the number if it's perfect and that is determined by isPerfect() which returns either true or false

Member Avatar for jmartzr1

Thank you both for helping me out. I am having trouble compiling the code as it is giving me an error: cannot find symbol regarding the if(isPerfect(i)) line of code. Any suggestions?

your code has an allperfect , isperfect , and possibly a main method right? it would be helpful if your post it here , then we might know what is causing the problem.

Member Avatar for jmartzr1

Yes, it has an allPerfect method, an isPerfect method, and it needs to have a class to call those methods with a main method. I'm honestly just confused about methods in general because I am unsure of how to combine them and make them run together. We are supposed to submit each method separately as an individual question with a class to run both of them. However, I think that is really confusing me. My isPerfect method is the same as before, but my allPerfect method is as follows:

import java.util.*;
public class allPerfect
{
    public void allPerfect(int end)
    {
        for(int i =1; i <= end; i++)
        {
            if(isPerfect(i))
            {
                System.out.println(i + "/n");
            }
        }
    }

    public static void main(String[] args)
    {
        allPerfect ap = new allPerfect();
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a value to see the perfect numbers up to and possiblyincluding that number.");
        int num = scan.nextInt();
        System.out.println(ap.allPerfect(num));

    }
}

I keep getting the erorr "cannot find symbol" and it refers to if(isPerfect(i))
^

individual question with a class to run both of them

sorry, i didnt get you there...

regarding your code , your creating isPerfect as a separate class , so when you want to use it inside your allPerfect class , you have to create a reference to it. since your calling it directly , it says it cannot find the class, as java doesnt know where to look for the isPerfect method.

also in this line System.out.println(ap.allPerfect(num)); this wont work as allPerfect()'s return type is void. you cannot print something when its not there!

Member Avatar for jmartzr1

The part where each individual question has to be submitted on it's own, but since both questions work off of one another, we are to use the same class to test them. I tried to reference it inside of my allPerfect class, but I don't know where to save/tell java where to look for it. Can you elaborate more or give an example on how to go about doing so? As for the last part about the system.out.println, sill mistake on my behalf. Thanks!

sure you know how to tell java where to look for what , you did it in your previous code as well :) whenever you write <something>.<another thing> in your code , your telling java to look for that "another thing" thing inside of that "something" thing.

in other words , if you write like isPerfect p = new isPerfect(); in your allPerfect method , your creating a reference, a remote control that the compiler can use from within your allPerfect method to have access to your isPerfect method of your isPerfect class. if both the methods were inside the same class , you wouldnt need the reference.

but now that you hve your reference , you can now access the isPerfect method like so :

instead of if(isPerfect(i)) , you now write if(p.isPerfect(i))
p is your remote , the reference to the isPerfect method , and using that , you can now use whatever methods you have inside of that class. in this case , the isPerfect() method.
(just one thing to remember , that you can call only those that are public, your remote wont give you access to the private stuff.)

edit: i noticed that the main method in the isPerfect method you have posted earlier, one that you said is the same as before , it is designed to check whether or not a single user input is perfect or not. but you want your code to check untill a specified range , and print out all the perfect numbers upto that range. as you see they arent the same , and you have to change your code to bring in that functionality.

i suggest you read the wiki page if you already havent. it has a lot of information you can implement in your code.

Member Avatar for jmartzr1

Alright, I understand exactly what you mean now! I was having some trouble undertsanding on how to reference something and access it. Thanks for the information! Now I modified my code a bit and created an isPerfect p = new isPerfect(); and put the if(p.isPerfect(i)) where it belongs, but now I am getting an error of missing return statement. Even though I have the return statement in there. Any suggestions?

MY updated code:

import java.util.*;
public class allPerfect
{
    public int allPerfect(int end)
    {
        isPerfect p = new isPerfect();
        for(int i =1; i <= end; i++)
        {
            if(p.isPerfect(i))
            {
                System.out.println(i + "/n");
                return i;
            }
        }
    }


    public static void main(String[] args)
    {
        allPerfect ap = new allPerfect();
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter a value to see the perfect numbers up to and possiblyincluding that number.");
        int num = scan.nextInt();
        ap.allPerfect(num);

    }
}

If one of your calls to isPerfect returns true then your allPerfect will execute the return on line 12, and that's OK. But if they all return false then allPerfect will drop out of the loop at line 13 and hit the end of the method without having executed a return statement. That's an error because your method is declared as returning an int.
To fix this you need another return statement so that no natter what happens in your if tests and loops your code always returns an int value.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.