What is perfect number?

A perfect number is that number which is equal to the sum of all its positive divisor without the number itself. In this guide we will see some C program related to perfect number.

Consider a number 28.

Now, we know that 28 is divisible by 1, 2, 4, 7, 14 and 28.

The sum of all its positive divisor without 28 (the number itself) is

= 1 + 2 + 4 + 7 + 14

= 28

So, 28 is a perfect number.

Again let’s consider the number 32 which is divisible by 1, 2, 4, 8, 18 and 32.

Now,

1 + 2 + 4 + 8 + 18

= 33

Which is not equal to 32 and for this 32 is not a perfect number.

If you have the clear idea about perfect number then let’s go ahead with some C program related to perfect number.

C program to check perfect number

In this C program we will take user input which will be an integer and then check that it is perfect number or not. We can do this program using different loop although we will use for loop here to check the number.

// c program to check perfect number

#include<stdio.h>
int main(){
  int c, number, reminder, sum = 0;
  printf("Enter a number to check : ");
  scanf("%d", &number);

  for(c = 1; c < number; c++){
    reminder = number % c;
    if(reminder == 0){
      sum += c;
    }
  }
  if(sum == number){
    printf("\n%d is a perfect number.\n", number);
  }else{
    printf("\n%d is not a perfect number.\n", number);
  }
return 0;
}

Output of perfect number program :

c-perfect-number-program-check-perfect-number

C program to find all perfect number between two integer

We will determine all the perfect number between two given integers by the user in this C program. At first we will take two integer as input from the user that will be the range. Then we will determine all the perfect number between them.

// program to find all perfect number between two integer in C

#include <stdio.h>
int main(){
  int c, n, firstNum, lastNum, sum = 0;

  printf("Enter first number here : ");
  scanf("%d", &firstNum);
  printf("Enter last number here : ");
  scanf("%d", &lastNum);

  printf("\nAll perfect number between %d and %d are : \n", firstNum, lastNum);

  for(n = firstNum; n <= lastNum; n++){

    for(c = 1, sum = 0; c < n; c++){
      if(n % c == 0){
        sum = sum + c;
      }
    }

    if(sum == n){
      printf("%d ", n);
    }

  }

  return 0;
}

Compile and run the program to get the following output :

Enter first number here : 1
Enter last number here : 5000000

All perfect number between 1 and 5000000 are :
6 28 496 8128

Previous pageStrong number program

Next pageSum of natural number