Summary: In this programming example, we will learn to check the perfect number in C and also learn to print all perfect numbers in the given range.
If the sum of all factors of a number ( exclusive itself ) is equal to the original number, then it’s a Perfect number. E.g. 6, 28, etc.
Steps to Check Perfect Number in C:
- Input a number.
- For loop from
i=0
toi<num/2
:- Check whether
i
is divisible bynum
. If yes, then add it to thesum
.
- Check whether
- After the loop is over, Check whether
sum == num
:- If yes, then the number is perfect, else not.
Here is the implementation of the steps in C:
#include <stdio.h>
int main()
{
int num, sum =0, i;
printf("Enter a Number \n");
scanf("%d",&num);
//A number greater than num/2 cannot be the divisor
for(int i=1; i<=num/2; i++){
//sum all the divisor
if(num%i == 0)
sum += i;
}
if(sum == num)
printf("Perfect Number \n");
else
printf("Not a Perfect Number \n");
return 0;
}
Output:
Enter a number6
Perfect Number
Print all Perfect Number in the Given Range
#include <stdio.h>
#include <stdbool.h>
/*
*function returns true if the passed number-
*is perfect,otherwise returns false
*/
bool isPerfect(int num){
int sum=0;
//sum of all divisor of num
for(int i=1; i<=num/2; i++){
if(num%i == 0)
sum +=i;
}
return num == sum;
}
int main(void) {
int i, up, low;
printf("Enter a lower and upper range value \n");
scanf("%d",&low);
scanf("%d",&up);
//Loop through all the numbers in the given range
for(int i=low; i<=up; i++){
if(isPerfect(i))
printf("%d ",i);
}
return 0;
}
Output:
Enter a lower and upper range value: 1 10006 28 496
In the above program, we have created a separate function that uses the same logic as the above program to check whether the passed number is a Perfect number or not.
We iterate through all the numbers in the given range and individually check them by passing the number to the isPerfect()
method.
In this tutorial, we learned to check whether a given number is a perfect number or not in the C programming language.
I want a program of fascinate number in c and java
Check out this: Fascinating number in C