alt

Check whether a given Number is a Perfect Number

Hi Guys. Welcome you all for the next article of  “C Programming – How to do it” series. Today we are going to write a program to check whether a given number is a perfect-number with a c program. Before the start our tutorial I have to do a little request. If you haven’t liked our Facebook Page yet, please like it to support us. (FB Page: BMaxx Edu). OK, let’s move to our stuff how to check a given Number is a Perfect Number

In the beginning, we have to learn what are the Perfect Numbers. “Perfect number is a positive integer that equals to the sum of its positive factors/divisors excluding itself. For example, divisors of six is 1,2,3 & 6. We neglect 6 and get the sum of 1,2 and 3. The sum is six. So six is a perfect number

Problem Solution

We have to do the following steps to get the answer.

  • Input a number.
  • Sort out the divisors of the given number.
  • Get the sum of divisors.
  • Compare the summation with the given number. If they are equal, it is a perfect number.

For sort out the devisors, we use a simple method. We get the remainder of the given number for every number between “0” and “given number”. For example when user input 6, we divide the 6 by 1,2,3,4 and 5 and get the remainder for each number. When the remainder equals to zero, it is a reminder of the given number.

EX: User input the 6
6%1 = 0  , 6%2 =0  6%3 =0 ,6%4 !=0 , 6%5 !=0
Devisors of 6 = 1,2,3

  Flow Chart of the Program

perfect number

Source Code

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num=0, rem=0 ,sum=0,i; // num= Given Number , rem= Remainder

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

for (i=1;i<num;i++)
{
if(num%i==0)
{
sum+=i; //Sum=Sum+i
}
}
if(sum==num)
{
printf(" %d is a Perfect Number",num);
}
else
{
printf(" %d is not a Perfect Number",num);
}

printf("\n \n A program by BMaxx @ Digital Chalie \a");
return 0;
}

 

In this program, we used a for loop and two if conditions. This is the easiest and the best way to write this program. There is a little challenge for you. Upgrade this program to find the perfect numbers of a given range. Try it and send your program code to us. First three completers will be rewarded.

Send your answers to contact@bmaxxblog.com

Bonomi Tharinda
Bonomi Tharinda is the Developer of the BMaxx Blog. He is a skilled web developer and graphic designer. In addition, he is an undergraduate student of a representative University in Sri Lanka. He is working as a tutor of an institute and as a part-time blogger, he will help you all to make your problems solved.Here are his social accounts and you can follow him through them.