Check for a perfect number
Determine whether a positive integer equals the sum of its positive divisors excluding itself.
Course progress
Problem 73 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
number = 28
Expected output
True
What is happening?
The positive divisors below 28 are 1, 2, 4, 7, and 14. They add to 28, so the number is perfect.
Solution strategy
Build the right mental model
Start with divisor 1, find factor pairs only through the square root, and avoid adding the square root twice for perfect squares.
Core concepts
number theory · factor pairs
Complexity
Time O(sqrt n), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for perfect-number-check
using System;
class Program
{
static bool IsPerfect(int number)
{
if (number <= 1) return false;
int sum = 1;
for (int divisor = 2; divisor <= number / divisor; divisor++)
{
if (number % divisor != 0) continue;
sum += divisor;
int pair = number / divisor;
if (pair != divisor) sum += pair;
}
return sum == number;
}
static void Main()
{
Console.WriteLine(IsPerfect(28));
}
}Knowledge check
Questions students often ask
What is the main idea behind check for a perfect number?
Start with divisor 1, find factor pairs only through the square root, and avoid adding the square root twice for perfect squares.
What is the time and space complexity of this solution?
Time O(sqrt n), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.