Skip to main content

ProwessApps

Learn · Practice · Excel

C Program to check a given number is Perfect number or not

C Code Example — Loop Programs

ADVERTISEMENT

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

  1. Read an integer n.
  2. Initialize sum = 0.
  3. Run a loop from i = 1 up to n / 2.
  4. Inside the loop, if i is a clean divisor of n (n % i == 0), add i to the sum.
  5. 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)
ADVERTISEMENT