Pefect Numbers ?
I'm having trouble with the code for my perfect numbers. It says that each number I enter is a perfect number.Can someone please look at it and see if they see anything wrong? Thanks.
public static boolean isPerfect(int number) {
boolean perfectInput = true;
int count = 0;
for(int x = 0; x <= number; x++){
if (x % number == 0){
count += x;
}
if(count == number){
perfectInput = true;
}
else
perfectInput = false;
}
return perfectInput;
}
x should start from 1, not 0.
and the termination condition should be <= (number / 2)
and you should have if (number % x == 0) , your code is reversed
Finally you should test the count == number outside the loop.
Note: you don't need a separate boolean, instead just type:
return (count == number);
You could optimise to public static boolean isPerfect(int number) {
return number==6 || number==28 || number==496 ||
number==8128 || number==33550336;
}
> You could optimise to public static boolean
> isPerfect(int number) {
>return number==6 || number==28 || number==496 ||
>number==8128 || number==33550336;
>
So few perfect numbers, I feel bad for them. Its the loneliest set since the set of 1 oooooooooooh.
isLoneliest(int number) {
return number == 1;
}