Subscribe Us

Perfect Number In C

Perfect Number

Perfect Number


C Program To Check Perfect Number or Not

In mathematics, a perfect number is a positive integer that is
equal to the sum of its positive divisors, excluding the number itself.

For Example,
28 is a positive number that is completely divisible by 1, 2, 4, 7 and 14.
We know that the number is also divisible by itself but we will exclude it in the addition of divisors.
When we add these divisors (1 + 2 + 4 + 7 + 14 = 28), it produces 28, which is equal to the number that we have considered.
So, we can say that 28 is a perfect number.

To check if a number is a Perfect Number or not
you can use the following algorithm:
  1. Read the input number.
  2. Initialize a variable sum to 0.
  3. Iterate through all the numbers from 1 to number/2 (excluding number itself).
    • For each iteration, check if the current number is a divisor of the input number.
    • If the current number is a divisor, add it to the sum.
  4. After the loop, check if the sum is equal to the input number.
    • If they are equal, the number is a Perfect Number; otherwise, it is not.
  5. Print the result.

This algorithm calculates the sum of the divisors of the input number and compares it with the input number to determine if it is a Perfect Number.

Here is an example implementation in C

Source Code

// C Program To Check Perfect Number
#include<stdio.h>
#include<conio.h>
   void main()
      {
         int num , i , sum = 0 ;
         printf("Enter a Number To Check : ");
         scanf("%d",&num);
         for( i=1; i<=num/2; i++ )
            {
                if(num%i==0)
                  {
                    printf("%d ",i);
                    sum = sum + i ;
                  }
            }
         printf("\nSum of Factors of a Given number : %d \n",sum);
         if(sum==num)
            printf("It is a Perfect Number . ");
         else
            printf("It is Not a Perfect Number . ");
         getch();
  }

Output

Sample Input :
Enter a Number To Check : 28
Sample Output:
1 2 4 7 14
Sum of Factors of a Given Number : 28
It is a Perfect Number

Sample Input :
Enter a Number To Check : 10
Sample Output:
1 2 5
Sum of Factors of a Given Number : 8
It is Not a Perfect Number

Looping Related Programs