ADVERTISEMENT
Perfect Number Between 1 and Given Input
In mathematics, a perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). This code finds and displays all perfect numbers within the specified range.
#include<stdio.h>
#include<math.h>
main()
{
int num,i,sum,j;
printf("Enter a number to know all perfect numbers till n\n");
scanf("%d",&num);
printf("The perfect numbers between 1 and %d are:",num);
for(i=1;i<=num;i++)
{
sum=0;
for(j=1;j<i;j++)
{
if(i%j==0)
{
sum+=j;
}
}
if(sum==i)
{
printf("%d\n",i);
}
}
}C Programming ExamplesOUTPUT
Enter a number to know all perfect numbers till n
9654
The perfect numbers between 1 and 9654 are:6
28
496
8128C Programming ExamplesExplanation:
Here’s a step-by-step explanation of the code:
Header File:
- The program includes the standard C library header <stdio.h> for input and output operations and <math.h> for mathematical operations.
Main Function:
- The main function is the entry point of the program.
Variable Declarations:
- int num, i, sum, j; Declares integer variables for storing user input, looping variables, and the sum of divisors.
Input for a Number:
- The user is prompted to enter a number using scanf, and the value is stored in the variable num.
Output Prompt:
- The code displays a message informing the user that it will find perfect numbers up to the value of num.
Finding Perfect Numbers:
- The code enters a for loop that iterates from 1 to num.
- For each number i in this range, it initializes the sum variable to 0.
- It then enters another for loop with variable j starting from 1 and iterating up to i-1.
- Within the inner loop, it checks if i is divisible by j (i.e., i % j == 0).
- If it is divisible, it adds j to the sum.
- After the inner loop finishes, it checks if the sum is equal to i. If it is, then i is a perfect number.
- If i is a perfect number, it is displayed using printf.
Output:
- The code lists all the perfect numbers found within the range from 1 to the user-provided number num.