A C program to check whether a given number is a perfect number or not. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). For example, 6 is a perfect number because its divisors (1, 2, 3) sum up to 6.
#include
int isPerfectNumber(int num) {
int sum = 0;
// Find divisors and sum them
for (int i = 1; i <= num / 2; i++) {
if (num % i == 0) {
sum += i;
}
}
return sum == num;
}
int main() {
int num;
// Input from user
printf("Enter a number: ");
scanf("%d", &num);
// Check if it's a perfect number
if (isPerfectNumber(num)) {
printf("%d is a perfect number.\n", num);
} else {
printf("%d is not a perfect number.\n", num);
}
return 0;
}
Explanation:
The ‘
isPerfectNumber'
function calculates the sum of all proper divisors of the given number.The ‘
for
‘ loop iterates up to ‘num/2
‘ because a number cannot be divisible by anything larger than half of itself (except itself).If the sum of the divisors equals the number, it is a perfect number.
The ‘
main
‘ function takes user input, calls ‘isPerfectNumber
‘, and displays the result.
Example Output:
Enter a number: 28
28 is a perfect number.
Enter a number: 10
10 is not a perfect number.