DevPath

← All problems

Perfect Number

Easy math

Description

Return true if the number equals the sum of its proper divisors.

Constraints

1 <= n <= 10^8

Examples

Input: n = 28

Output: true

Hints (1)
  • Sum divisors up to the square root, adding both members of each pair.

Solutions

Divisor pairs to square root. · Time O(sqrt n) · Space O(1)

func checkPerfectNumber(n int) bool {
    if n <= 1 {
        return false
    }
    sum := 1
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            sum += i
            if i != n/i {
                sum += n / i
            }
        }
    }
    return sum == n
}

Create a free account to submit solutions, track progress and save problems.

Create account