1
class Solution {
2
public:
3
bool checkPerfectNumber(int num) {
4
// we are initialising sum with 1 instead of 0 because 1 will be divisor of
5
// every number
6
int sum = 1;
7
for (int i = 2; i < sqrt(num); i++) {
8
if (num % i == 0) {
9
// it checks if both are same factors, for ex, if num=9, i=3, num/i is
10
// also equal to 3. It is done so that repeated factors aren't added.
11
if (i == num / i) {
12
sum += i;
13
} else {
14
// we are adding n/i because since we are running the loop for
15
// sqrt(num), we will be missing divisors >sqrt(num) so tto include
16
// that factor we'll add num/i; for ex if we have 64 as number than 8
17
// is sqrt but 16 and 32 also divides 64 but our loop won't consider
18
// that case; so we are adding num/i, which means with 2 we are adding
19
// 32 and with 4 we are adding 16.
20
sum += i + num / i;
21
}
22
}
23
}
24
if (sum == num && num != 1) {
25
return true;
26
}
27
return false;
28
}
29
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0