Math · Easy

Perfect Number Check

Solve it on DeVert Campus - free code runner

Problem

A positive integer n is called a perfect number if it equals the sum of its proper divisors (all positive divisors of n excluding n itself). For example, 6 = 1 + 2 + 3. Given an integer n, determine whether it is a perfect number.

Input and output

Input: A single line containing one integer n. Output: Print "YES" if n is a perfect number, otherwise print "NO".

Example

Input:
28
Output:
YES

Constraints

1 <= n <= 10^8

Key observation

Excluding n ITSELF from the sum (even though n divides itself) is the crucial detail that distinguishes 'proper divisors' from 'all divisors' - a common source of off-by-one-style bugs if not handled explicitly.

Intuition

Check whether a number equals the sum of all its proper divisors (every divisor except itself). Brute force: Check every integer from 1 to n-1 to see if it divides n, summing the ones that do - this costs O(n), unnecessary given that divisors can be found much faster by checking only up to sqrt(n). Optimised: Since divisors always come in PAIRS (i and n/i) around the square root, checking only up to sqrt(n) finds every divisor pair in O(sqrt(n)) instead of scanning the whole range up to n - a direct application of the same 'divisors pair around the square root' insight used in prime checking.

Step by step

1. Find all divisors of n by checking every i from 1 up to sqrt(n) - whenever i divides n, BOTH i and n/i are divisors. 2. Sum every PROPER divisor (every divisor except n itself). 3. Compare the total to n - if they match, n is perfect.

Complexity

Time: O(sqrt(n)) - checking divisor pairs only up to the square root. Space: O(1) - just a running sum.

Edge cases

n=1 has no proper divisors, so its divisor sum is 0, which is not equal to 1 (not perfect). Perfect numbers are extremely rare - within this problem's bound the only ones are 6, 28, 496, 8128, and 33550336.

Interview tip

Be careful about the special case where i equals n/i (a perfect square divisor) - counting it TWICE would incorrectly inflate the sum, so it should only be added once.

All DSA problems