Aim:
To write a ‘C’ program to find whether the given number is perfect number or not.
A number is a perfect number if the sum of the factors of the number other than itself is equal to that number.
Example: 28=1+2+4+7+14 is a perfect number.
Algorithm:
- Read the number n.
- If the number is less than 0 goto step 7
- Initialize sum=0, i=1
- if n % i=0 then sum=sum+i
- Increment i. If i<n goto step 4
- if sum=n
Print the number is a perfect number
else
Print the number is not a perfect number
- Stop.
Program:
/* To find whether the given number is perfect number */
#include<stdio.h>
#include<conio.h>
void main()
{
int n,sum=0,i;
clrscr();
printf("Enter a number:");
scanf("%d",&n);
if(n>0)
{
for(i=1;i<n;i++)
if(n%i==0) sum=sum+i;
if(sum==n)
printf("\n\t%d is a perfect number",n);
else
printf("\n\t%d is not a perfect number",n);
}
else
printf("\n\tThe input number should be greater than zero");
getch();
}
Output -1:
Enter a number:28
28 is a perfect number
Output-2:
Enter a number:56
56 is not a perfect number
Output-3:
Enter a number:-28
The input number should be greater than zero
No comments:
Post a Comment