C Program to Check Perfect Number with Output and Explanation
for loop and compares the sum to the number; if equal, it prints "Perfect number", else "Not perfect number".Examples
How to Think About It
% operator, add those divisors, and then compare the sum to the original number. If they match, the number is perfect.Algorithm
Code
#include <stdio.h> int main() { int num, sum = 0; printf("Enter a number: "); scanf("%d", &num); for (int i = 1; i < num; i++) { if (num % i == 0) { sum += i; } } if (sum == num) { printf("%d is a Perfect number\n", num); } else { printf("%d is Not a Perfect number\n", num); } return 0; }
Dry Run
Let's trace the input 6 through the code to see how it checks for a perfect number.
Input number
num = 6, sum = 0
Loop i from 1 to 5
Check divisors and add to sum
i=1
6 % 1 == 0, sum = 0 + 1 = 1
i=2
6 % 2 == 0, sum = 1 + 2 = 3
i=3
6 % 3 == 0, sum = 3 + 3 = 6
i=4
6 % 4 != 0, sum = 6
i=5
6 % 5 != 0, sum = 6
Compare sum and num
sum = 6, num = 6, equal -> Perfect number
| i | num % i == 0? | sum |
|---|---|---|
| 1 | true | 1 |
| 2 | true | 3 |
| 3 | true | 6 |
| 4 | false | 6 |
| 5 | false | 6 |
Why This Works
Step 1: Find divisors
The program checks every number less than the input to see if it divides the input evenly using num % i == 0.
Step 2: Sum divisors
All divisors found are added together in the sum variable.
Step 3: Compare sum to number
If the sum of divisors equals the original number, it means the number is perfect.
Alternative Approaches
#include <stdio.h> int main() { int num, sum = 0, i = 1; printf("Enter a number: "); scanf("%d", &num); while (i < num) { if (num % i == 0) { sum += i; } i++; } if (sum == num) { printf("%d is a Perfect number\n", num); } else { printf("%d is Not a Perfect number\n", num); } return 0; }
#include <stdio.h> int main() { int num, sum = 0; printf("Enter a number: "); scanf("%d", &num); for (int i = 1; i <= num / 2; i++) { if (num % i == 0) { sum += i; } } if (sum == num) { printf("%d is a Perfect number\n", num); } else { printf("%d is Not a Perfect number\n", num); } return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program loops from 1 to n (or n/2 in optimized), checking divisibility each time, so time grows linearly with input size.
Space Complexity
Only a few variables are used regardless of input size, so space complexity is constant.
Which Approach is Fastest?
The optimized approach checking divisors up to n/2 is faster than checking up to n, but both are O(n). Using more advanced math can reduce time further but is more complex.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop up to n | O(n) | O(1) | Simple understanding |
| While loop up to n | O(n) | O(1) | Alternative loop style |
| For loop up to n/2 | O(n/2) ~ O(n) | O(1) | Better efficiency |