Question

I wrote these two methods to determine if a number is perfect. My prof wants me to combine them to find out if there is an odd perfect number. I know there isn't one(that is known), but I need to actually write the code to prove that.

The issue is with my main method. I tested the two test methods. I tried debugging and it gets stuck on the number 5, though I can't figure out why. Here is my code:

public class Lab6
{
public static void main (String[]args)
{
  int testNum = 3;

  while (testNum != sum_of_divisors(testNum) && testNum%2 != 2)
     testNum++;

}

public static int sum_of_divisors(int numDiv)
{
  int count = 1;
  int totalDivisors = 0;

  while (count < numDiv)
     if (numDiv%count == 0)
     {
        totalDivisors = totalDivisors + count;
        count++;
     }
     else
     count++;

  return totalDivisors;
}

public static boolean is_perfect(int numPerfect)
{
  int count = 1;
  int totalPerfect = 0;

  while (totalPerfect < numPerfect)
  {
     totalPerfect = totalPerfect + count;
     count++;
  }
  if (numPerfect == totalPerfect)
     return true;
  else
     return false;
}
}
Was it helpful?

Solution

Make

testNum%2 != 2

as

testNum%2 != 0

OTHER TIPS

testNum=3
while (testNum != sum_of_divisors(testNum) && testNum%2 != 2)
    testNum++;

You may want to do 'testNum+=2' since you are concerned about only odd numbers and replace the testNum %2!=2 with testNum>0 or other stopping condition. Eventually your integers will overflow.

"My prof wants me to combine them to find out if there is an odd perfect number. I know there isn't one(that is known), but I need to actually write the code to prove that."

Do you mean between 3 & 2^32-1? It is not known that there are no odd perfect numbers.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top