perfect number program in c
This program takes an input value from the user and checks a number is a perfect number or not. A perfect number is a positive number which is equal to the sum of all its divisors excluding itself. For example: 28 is a perfect number as 1 + 2 + 4 + 7 + 14 = 28.
#include <stdio.h>
int main()
{
int n,i,sum=0;
printf("\nEnter a value: ");
scanf("%d",&n);
for(i=1; i<=n/2; i++)
{
if(n%i==0)
sum+=i; //sum=sum+i;
}
if(n==sum&&n!=0)
printf("\n%d IS PERFECT NUMBER",n);
else
printf("\n%d IS NOT PERFECT NUMBER",n);
return 0;
}
[quote]
Output:
Enter a value: 28
28 IS PERFECT NUMBER
[/quote]
Find perfect numbers within a range
This program takes two input values from user and print all perfect numbers between the range of those values
#include <stdio.h>
int main()
{
int n,n1,n2,i,sum,count=0;
printf("\nEnter a value: ");
scanf("%d%d",&n1,&n2);
for(n=n1; n<=n2; n++)
{
sum=0;
for(i=1; i<=n/2; i++)
{
if(n%i==0)
sum+=i;
}
if(n==sum)
printf("\n%d.PERFECT NO:%d",++count,n);
if(count==4)
break;
}
return 0;
}
[quote]
Output:
Enter a value: 1 12345
1.PERFECT NO:6
2.PERFECT NO:28
3.PERFECT NO:496
4.PERFECT NO:8128
[/quote]