C Program to find Perfect Number

In this blog post, we learn how to write a C Program to find Perfect Number?. We will write the C program to find Perfect Number using the Arithmetic Operators. Write a function to check if a given number is perfect or not. How to check the perfect number in C programming using loop. Logic to check perfect number in C programming.

What is the perfect number?

A perfect number is a positive integer which is equal to the sum of its proper positive divisors excluding the number itself. Let see an example,

Input: n = 6

Proper divisors of 6 are 1, 2, 3

Sum of its proper divisors = 1 + 2 + 3 = 6

Hence 6 is a perfect number.

 

Algorithm to check Perfect number:

  • Ask the user to enter an integer number.
  • Initialize another variable with 0 to store the sum of proper positive divisors.
  • Go through every number from 1 to n/2 and check if it is a divisor. Maintain the sum of all divisors. If the sum becomes equal to n, then the number will be a perfect number else it will be not a perfect number.

 

#include <stdio.h>


int main()
{
    int i, num, sum = 0;

    //Ask user to enter a number
    printf("Enter any number = ");
    scanf("%d", &num);

    // Calculate sum of all proper divisors
    for(i = 1; i <= num / 2; i++)
    {
        //if i is a proper divisor of num
        if(num%i == 0)
        {
            sum += i;
        }
    }

    // Check whether the sum of proper
    //divisors is equal to num or not
    if(sum == num)
    {
        printf("%d is perfect number", num);
    }
    else
    {
        printf("%d is not perfect number", num);
    }

    return 0;
}

Output:

Enter any number = 6
6 is a perfect number

 

Find Perfect Number using the function:

 

#include <stdio.h>


//return 1 is perfect number either return 0
int isPerfect(int num)
{
    int i,sum = 0;

    // Calculate sum of all proper divisors
    for(i = 1; i <= num / 2; i++)
    {
        //if i is a proper divisor of num
        if(num%i == 0)
        {
            sum += i;
        }
    }

    return (sum == num);
}

int main()
{
    int num;

    printf("Enter number = ");
    scanf("%d",&num);

    isPerfect(num)? printf("Perfect number"):printf("Not a perfect number");

    return 0;
}

Output:

Enter number = 6
Perfect number