A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. For instance, 28 is a perfect number because its divisors are 1, 2, 4, 7, and 14, and 1 + 2 + 4 + 7 + 14 = 28.
Write a function that checks whether a given number is a perfect number.
true
or false
) indicating whether the given number is a perfect number?Let’s assume:
#include <iostream>
#include <cmath>
class Solution {
public:
bool checkPerfectNumber(int num) {
if (num <= 1) return false; // No perfect number less than or equal to 1
int sum = 1; // Start with 1 because 1 is a divisor of all numbers
int sqrtNum = std::sqrt(num);
for (int i = 2; i <= sqrtNum; i++) {
if (num % i == 0) {
sum += i;
if (i != num / i) {
sum += num / i;
}
}
}
return sum == num;
}
};
int main() {
Solution solution;
int num = 28;
std::cout << "Is " << num << " a perfect number? " << (solution.checkPerfectNumber(num) ? "Yes" : "No") << std::endl;
return 0;
}
false
as there are no perfect numbers less than or equal to 1.i
is a divisor, add i
and also add the corresponding divisor num / i
(if it’s different from i
).num
.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?