I am trying to make a program that will show if an input is a perfect number meaning the factors (not including the number) add up to be the same as that number. I got it working other than the return value. I want to return true if the sum of the factors is equal to the number entered however it just won't do it.
I have tried moving the if statement all over the code and it doesn't work anywhere.
public class Main {
public static void main(String[] args) {
isPerfectNumber(28);
}
public static boolean isPerfectNumber(int number) {
if (number < 1) {
return false;
}
int numberToTest = 1;
int sumOfFactors = 0;
while (numberToTest < number) {
if (number % numberToTest == 0) {
sumOfFactors += numberToTest;
}
numberToTest++;
}
if (sumOfFactors == number) {
return true;
}else{
return false;
}
}
}
I expect that when the code see that the sumOfFactors will have the sum = to the number entered and that's when I get the true statement however when that happens it doesn't return true. In fact, it doesn't return anything and states that the method returns were not used.
It "isn't working" because you aren't printing the result.
public static void main(String[] args) {
isPerfectNumber(28);
}
should be
public static void main(String[] args) {
System.out.println(isPerfectNumber(28));
}
which is "true". Also,
if (sumOfFactors == number) {
return true;
} else {
return false;
}
is a long way to write
return sumOfFactors == number;
And, if you're using Java 8+, your isPerfectNumber
method can be written as a one-liner with an IntStream
and a lambda filter like
public static boolean isPerfectNumber(int number) {
return number >= 1 && IntStream //
.range(1, number) //
.filter(i -> number % i == 0) //
.sum() == number;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.