Perfect Numbers are those numbers which are equal to the sum of its proper positive divisors (excluding itself). Consider number 6, it has only four proper positive divisors 1, 2, 3 and 6. If we exclude 6, proper divisors left are 1, 2 and 3 and their sum is 6 which is equal to the number itself. So, 6 is a Perfect Number.
You can also say that Perfect Number is half the sum of all of its proper positive divisors. For 6, its proper divisors are 1, 2, 3 and 6 and their sum is 12. Now as 6 is half of this sum, 6 is a Perfect Number. You can learn more about Perfect Numbers on Wikipedia.
In this tutorial, I will show you a C language code to test whether a given number is Perfect Number or not.
Algorithm:
- Let
abe the number which is to be checked. - Let
tempandsumbe a temporary numbers initialized to 1 and 0 respectively. - Now check whether
tempis less thanaor not. If not, move to step 7, otherwise step 4. - Check if
tempperfectly divides given numberaor not. If yes move to next step, otherwise to step 6. - Add value of
temptosumand store the result insumitself. - Increment the value of
tempby 1 and move to step 3. - Check whether value of variable
sumis equal to given number or not. If yes, then given number is a Perfect Number, otherwise the given number is not a Perfect Number.
Instructions:
- We only need a single header file for this program to work.
#include <stdio.h>
- Now ask the user to enter the number he/she wants to check.
printf("Enter the numbers you want to check : "); scanf("%d", &num); - Now call the function
isPerfectwith the given number as parameter and store the returned value in a temporary variable. Check if the value of temporary variable is 1 or not. If it is 1, then given number is Perfect Number otherwise not.
HereisPerfectfunction is explained in next point and this function checks whether the argument is a Perfect Numberor not, if yes it returns 1, otherwise 0.temp = isPerfect(num); if(temp == 1) printf("%d is a Perfect Number...", num); else printf("%d is not a Perfect Number...", num); - In
isPerfectfunction, using two variablessumandtempand using a while loop (which will run until value oftempis less than given number), check whethertempperfectly divides given number, if it divides the number perfectly then add its value tosumvariable and store result insumitself. Also increment the value oftempin every iteration. After while loop check whether value ofsumvariable is equal to given number, if yes return 1, otherwise return 0.
int isPerfect(int num) { int temp = 1, sum = 0; while(temp < num) { if(num % temp == 0) sum += temp; temp++; } if(num == sum) return 1; else return 0; }
Here are some screenshots of the running sample code.
You can also download the sample working code from here.

