I have tried this using alittle more 'advanced' javaAnd exactly what part are you having trouble with?
like arrays and collections, but I dont quite get
them yet. What I need to do is find perfect numbers
by checking divisors of numbers and adding them up.
If the divisors of a number sum up to that number,
, then its perfect. I need to test a few different
numbers so how would you guys write it out.
I have tried a few different ways but nothing has
worked so far.
import java.io.*;
public class Testing
{
public static void main (String[] args) throws IOException
{
int testnumber = 4; //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)
{
testdivisor=1;
System.out.println("1st while");
while (testdivisor<=testnumber)
{
testdivisor++;
System.out.println("2nd while");
while (testdivisor % testnumber !=0)
{
testdivisor++;
System.out.println("3rd while");
}
if (divisor1==0)
{
divisor1=testdivisor;
}
if (divisor2==0)
{
divisor2=testdivisor;
}
if (divisor3==0)
{
divisor3=testdivisor;
}
if (divisor3==0)
{
divisor4=testdivisor;
}
}
if ((divisor1+divisor2+divisor3+divisor4)==testnumber)
{
System.out.println(testnumber);
hits++;
divisor1=0;
divisor2=0;
divisor3=0;
divisor4=0;
System.out.println("final");
}
else if ((divisor1+divisor2+divisor3+divisor4)!=testnumber)
{
testnumber++;
divisor1=0;
divisor2=0;
divisor3=0;
divisor4=0;
System.out.println("WRONG");
}
}
}
}
int total = 0;
for(int i=1; i<n; i++){
if(n%i == 0) total+=i;
}
System.out.println("n = "+n+" sum of divisors = "+total);
just look at every number and see if it is a divisor of n and if it is, add it to the total. If you want to do something more and see how it arrives at its answersint total = 0;
for(int i=1; i<n; i++){
if(n%i == 0){
total+=i;
System.out.println("divisor ="+i+" subtotal="+total);
}
}
System.out.println("n = "+n+" sum of divisors = "+total);