#include <stdio.h>
// Function to check if a number is perfect
int isPerfect(int num) {
int sum = 0; // Initialize sum of divisors
// Loop to find divisors and sum them
for (int i = 1; i <= num / 2; i++) { // Only need to check up to num/2
if (num % i == 0) { // Check if i is a divisor
sum += i; // Add divisor to sum
}
}
// Check if sum of divisors equals the number
return sum == num; // Return 1 (true) if perfect, else 0 (false)
}
int main() {
int number;
// Prompt user for input
printf("Enter a positive integer: ");
scanf("%d", &number);
// Check for valid input
if (number <= 0) {
printf("Please enter a positive integer.\n");
} else {
// Check and display if the number is perfect
if (isPerfect(number)) {
printf("%d is a perfect number.\n", number);
} else {
printf("%d is not a perfect number.\n", number);
}
}
return 0;
}
Explanation of the Code
Calls the is Perfect
function and displays the result.
Header Files: We include stdio.h
to use standard input and output functions.
Function isPerfect(int num)
:
Initializes a variable sum
to keep track of the sum of divisors.
Uses a loop to find divisors from 1
to num / 2
(since a number cannot be divisible by a number larger than half of itself).
If i
is a divisor (i.e., num % i == 0
), it adds i
to sum
.
Finally, it checks if the sum
equals the original number, returning 1
if true (perfect) or 0
if false (not perfect).
Main Function:
Prompts the user to enter a positive integer.
Checks if the input is valid (greater than 0).
Output
Enter a positive integer: 6
6 is a perfect number.
Enter a positive integer: 10
10 is not a perfect number.
Enter a positive integer: -5
Please enter a positive integer.