A perfect number is a positive integer which is equal to the sum of its divisors except the number itself. Examples of perfect numbers are: 6 and 28.
Below is a C program which allows a user to enter a number as input and print all the perfect numbers in the range 1 to the given number:
/*Program to print perfect numbers in the range 1 - user defined number*/
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,num,sum;
clrscr();
printf("Enter a number:");
scanf("%d",&num);
printf("\nPerfect numbers in the range 1 - %d are:\n",num);
for(i=1;i<=num;i++)
{
sum = 0;
/*Logic to check whether a number is perfect number or not*/
for(j=1;j<i;j++)
{
if(i%j==0)
{
sum = sum + j;
}
}
if(sum==i)
{
printf("%d\t",i);
}
}
getch();
}
Sample input and output:
Enter a number: 100
Perfect numbers in the range 1 - 100 are:
6 28
No comments:
Post a Comment