Overview:
Perfect number is a positive integer which is equal to the sum of its proper positive divisors. In this article I will demonstrate how to check perfect numbers. After all, I will write the logic of a C program to check if the number is perfect or not then I will write the C program to check the perfect number with output.
Table of contents:
- What is a Perfect Number?
- Demonstration to check perfect number
- Logic to check perfect number
- C program to check perfect number
- Explanation of the C program to check perfect number with output.
- Conclusion
What is a Perfect Number?
Perfect number is a positive integer which is equal to the sum of its proper positive divisors. For example: 6 is the first perfect number
Proper divisors of 6 are 1, 2, 3
Sum of its proper divisors = 1 + 2 + 3 = 6.
Hence 6 is a perfect number.
Demonstration to check perfect number
Logic to generate random number
- Step 1: Input a number from user. Store it in some variable say num.
- Step 2: Initialize another variable to store sum of proper positive divisors, say sum = 0.
- Step 3: Run a loop from 1 to num/2, increment 1 in each iteration.
- Step 4: The loop structure should look like for(i=1; i<=num/2; i++).
- Step 5: Why iterating from 1 to num/2, why not till num? Because a number does not have any proper positive divisor greater than num/2.
- Step 6: Inside the loop if current number i.e. i is proper positive divisor of num, then add it to sum.
- Step 7: Finally, check if the sum of proper positive divisors equals to the original number.
- Step 8: Then, the given number is Perfect number otherwise not.
C program to check perfect number
#include int main() { int i, num, sum = 0; /* Input a number from user */ while(1) { printf("Enter any number to check perfect number: "); scanf("%d", &num); /* Calculate sum of all proper divisors */ for(i = 1; i <= num / 2; i++) { /* If i is a divisor of num */ if(num%i == 0) { sum += i; } } /* Check whether the sum of proper divisors is equal to num */ if(sum == num) { printf("\n%d is Perfect Number\n", num); } else { printf("\n%d is Not Perfect Number\n", num); } } return 0; }
The output of the Program with code:
Conclusion:
Perfect number is a positive integer which is equal to the sum of its proper positive divisors. After the successful compilation of the program, this program displays the following output: Enter any number to check perfect number: If user enters 6 then it displays a message like 6 is a perfect number.