C# Program to Check if a Number is Perfect

A perfect number is a positive integer that equals the sum of its proper divisors (all divisors excluding the number itself). For example, 6 is perfect because its proper divisors (1, 2, and 3) sum to 6. Proper divisors are numbers that divide evenly into the given number without leaving a remainder.

Perfect Number: 6 1 2 3 = 6 6 ÷ 1 = 6 6 ÷ 2 = 3 6 ÷ 3 = 2 Sum of proper divisors: 1 + 2 + 3 = 6 Perfect Number!

Examples

Example 1 Perfect Number

  • Input: Number = 28
  • Output: True

Explanation: The proper divisors of 28 are 1, 2, 4, 7, and 14. Their sum is 1 + 2 + 4 + 7 + 14 = 28, which equals the original number.

Example 2 Not a Perfect Number

  • Input: Number = 15
  • Output: False

Explanation: The proper divisors of 15 are 1, 3, and 5. Their sum is 1 + 3 + 5 = 9, which does not equal 15.

Example 3 Large Perfect Number

  • Input: Number = 496
  • Output: True

Explanation: The proper divisors of 496 are 1, 2, 4, 8, 16, 31, 62, 124, and 248. Their sum equals 496.

Algorithm

To check if a number is perfect, we need to find all its proper divisors and calculate their sum. Here's the approach

  1. Handle edge cases: numbers less than or equal to 0 cannot be perfect.
  2. Initialize a sum variable to store the total of divisors.
  3. Loop from 1 to N/2 (since no proper divisor can exceed N/2).
  4. For each number i, check if it divides N evenly (N % i == 0).
  5. If yes, add i to the sum.
  6. Return true if sum equals the original number.

Implementation

Using Iterative Approach

using System;

class Program {
    static bool IsPerfectNumber(int number) {
        // Handle edge cases
        if (number 

The output of the above code is

6 is a perfect number.
28 is a perfect number.
15 is not a perfect number.
496 is a perfect number.
0 is not a perfect number.

Optimized Approach

We can optimize the algorithm by only checking divisors up to the square root of the number

using System;

class Program {
    static bool IsPerfectNumberOptimized(int number) {
        if (number 

The output of the above code is

8128 is a perfect number.
100 is not a perfect number.

Time and Space Complexity

Approach Time Complexity Space Complexity
Iterative (Basic) O(n) O(1)
Optimized O(?n) O(1)

Conclusion

A perfect number equals the sum of its proper divisors. The iterative approach checks all divisors up to n/2, while the optimized version only checks up to ?n for better performance. Perfect numbers are rare the first few are 6, 28, 496, and 8128.

Updated on: 2026-03-17T07:04:36+05:30

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements