4 Replies Latest reply on Jan 6, 2005 5:32 PM by 807596

# Finding Divisors and adding them up to find Perfect numbers - Program

I need my program to be able to find the first 4 perfect numbers. It is a perfect number if all of its divisors add up to the number. So 6 is the first one (1+2+3=6)

My program compiles, but when it runs it doesnt do anything. It must be getting stuck in one of my while loops or something. I cannot spot where the code is wrong but can anyone else see it?
``````import java.io.*;

public class Proj05b
{
public static void main (String[] args) throws IOException
{
int testnumber = 2;               //the testing number
int testdivisor = 1;          //the test divisor
int divisors;                    //the amount of divisors
int divisor1 = 0;               //the value of 1st divisor
int divisor2 = 0;               //2nd divisor
int divisor3 = 0;               //3rd divisor
int divisor4 = 0;               //4th divisor
int hits2 = 0;
int hits = 0;                    //# Of hits the last if statement has,
//once it reaches 4 it ends program

while (hits < 4)
{
testnumber++;               //Testing the next number
testdivisor = 1;          //Resetting the testdivisor
hits2 = 0;

while (hits2 == 0) //Making sure testdivisor isn't
{                                          //over half the number, needless
while (testdivisor <= testnumber)
{
divisors = (testnumber % testdivisor);

if  (divisors==0)
{

if (divisor1==0)
{
divisor1=testdivisor;
}
else if (divisor2==0)
{
divisor2=testdivisor;
}
else if (divisor3==0)
{
divisor3=testdivisor;
}
else if (divisor4==0)
{
divisor4=testdivisor;
}
}

if ((divisor1+divisor2+divisor3+divisor4)==testnumber)
{
System.out.println(testnumber);
hits2++;
hits++;
}
else if ((divisor1+divisor2+divisor3+divisor4)!=testnumber)
{
testdivisor++;
}
}
}
}
}
}``````
• ###### 1. Re: Finding Divisors and adding them up to find Perfect numbers - Program
Hmmm...punchout renamed? Or someone in the same class? You make the call.