A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For example, 28 is a perfect number because its divisors are 1, 2, 4, 7, 14, and 28, and 1 + 2 + 4 + 7 + 14 = 28.
Write a function that checks if a given number is a perfect number.
true
if the number is a perfect number and false
otherwise.false
for the input 1.public class PerfectNumber {
public static boolean checkPerfectNumber(int num) {
if (num <= 1) {
return false;
}
int sum = 1;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
sum += i;
if (i != num / i) {
sum += num / i;
}
}
}
return sum == num;
}
public static void main(String[] args) {
int n = 28;
System.out.println(checkPerfectNumber(n)); // should return true
}
}
num
is less than or equal to 1, it cannot be a perfect number, so we return false
.sum
to 1 (since 1 is always a divisor for any number larger than 1).num
. For each i
:
i
is a divisor of num
, add both i
and num/i
to the sum (if they are distinct).sum
with num
. If they are equal, return true
, otherwise return false
.num
.1
which should return false
.6
and larger ones like 28
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?