I’ve beeen trying to get a program written for a lab for class, and I believe I almost have it, but it won’t add up the divisors (div in the code) to the sum and return true if it is a perfect number and false otherwise. My code compiles and runs fine but will only return a false, presumably because sum is staying at 1 (it initializes at one since 1 is a divisor of every number). number is a private int brought in from the constructors and set statements.
public boolean isPerfect()
{
int x = number -1 ;
int div = 0;
int sum = 1;
while(x> 1)
{
if(number % x == 0)
{
div = x;
sum=+ div;
}
x--;
}
if(sum == number)
{
return true;
}
else
{
return false;
}
}
As well as the
+=/=+issue, your code also says that 1 is a perfect number, which is incorrect (6 is the first perfect number). This is because you start with asumof 1, the loop won’t execute at all, then you comparesumandnumber, which are equal for 1. You could just add a check for this special case, e.g.Additional tip – instead of :
You can just use: