Perfect Number

easy math

Problem

A perfect number is a positive integer that equals the sum of its positive proper divisors (excluding itself). Return true if num is a perfect number.

Inputnum = 28
Outputtrue
1 + 2 + 4 + 7 + 14 = 28.

def check_perfect_number(num):
    if num <= 1:
        return False
    total = 1
    d = 2
    while d * d <= num:
        if num % d == 0:
            total += d
            if d != num // d:
                total += num // d
        d += 1
    return total == num
function checkPerfectNumber(num) {
  if (num <= 1) return false;
  let total = 1;
  for (let d = 2; d * d <= num; d++) {
    if (num % d === 0) {
      total += d;
      if (d !== num / d) total += num / d;
    }
  }
  return total === num;
}
class Solution {
    public boolean checkPerfectNumber(int num) {
        if (num <= 1) return false;
        int total = 1;
        for (int d = 2; d * d <= num; d++) {
            if (num % d == 0) {
                total += d;
                if (d != num / d) total += num / d;
            }
        }
        return total == num;
    }
}
bool checkPerfectNumber(int num) {
    if (num <= 1) return false;
    int total = 1;
    for (int d = 2; d * d <= num; d++) {
        if (num % d == 0) {
            total += d;
            if (d != num / d) total += num / d;
        }
    }
    return total == num;
}
Time: O(√n) Space: O(1)