Skip to content

507. Perfect Number 👎

  • Time: $O(\sqrt{n}) \to O(1)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  bool checkPerfectNumber(int num) {
    if (num == 1)
      return false;

    int sum = 1;

    for (int i = 2; i <= sqrt(num); ++i)
      if (num % i == 0)
        sum += i + num / i;

    return sum == num;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public 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 + num / i;

    return sum == num;
  }
}
1
2
3
class Solution:
  def checkPerfectNumber(self, num: int) -> bool:
    return num in {6, 28, 496, 8128, 33550336}