C Program to check a given number is Perfect number or not
Objective
Write a C program to check if a given number is a Perfect Number.
Algorithm / Approach
- Read an integer
n. - Initialize
sum = 0. - Run a loop from
i = 1up ton / 2. - Inside the loop, if
iis a clean divisor ofn(n % i == 0), addito the sum. - After the loop, if
sum == n, the number is Perfect.
main.c
#include<stdio.h>
int main( ) {
int n, sum = 0, i ;
printf("Enter a number : ");
scanf("%d",&n);
for(i = 1; i<=n/2; i++) {
if(n%i==0) {
sum = sum+i;
}
}
if(sum == n) {
printf("%d is a perfect no.\n",n);
}
else {
printf("%d is not a perfect no.\n",n);
}
return 0;
}
Expected Output
Enter a number : 28 28 is a perfect no.
Explanation of the Program
- A Perfect Number is a positive integer that is strictly equal to the sum of its proper divisors (excluding itself).
- For example, the proper divisors of 28 are 1, 2, 4, 7, and 14. If you add them up (1+2+4+7+14), the sum is exactly 28.
- We optimize the loop by only going up to
n / 2, because a number cannot have any proper divisors larger than half of itself.
Complexity
Time Complexity
O(n) - Loop runs n/2 times.
Space Complexity
O(1)