Perfect Number Program in C
In mathematics, a perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself.
For example, 6 is a positive number that is completely divisible by 1, 2, and 3. We know that the number is also divisible by itself but we will include it in the addition of divisors. When we add these divisors (1 + 2 + 3 = 6), it produces 6, which is equal to the number that we have considered. So, we can say that 6 is a perfect number.
There are two ways to find the perfect number:
Using for Loop
Write a C program that accepts an input from the user and checks the given number is a perfect or not.
In the above output, the loop condition is validated at each iteration and counter i is incremented by 1. Inside the loop, various operations are performed such as:
Step 1: i = 1, rem = num % i, => 28 % 1 = 0. Here rem = 0.
Step 2: rem == 0, condition true.
Step 3: sum = 0 + i, sum = 0 + 1 => 1
// i is incremented by 1
Step 4: i = 2, rem = num % i, => 28 % 2 = 0. Here rem != 0, Condition is true;
Sum = 1 + i => 1 +2 = 3
Step 5: i = 3, rem = num % i, => 28 % 3 = 1. Here rem = 0, Condition is false;
Step 6: i = 4, rem = num % i, => 28 % 4 = 0. Here rem == 0, Condition is true;
Sum = 1 + i => 3 + 4 = 7
Similarly, check all condition;
Step 7: Sum == num, 28 == 28, Print the message "Entered number is a Perfect Number"
Using while Loop
Example 2: Let's create a C Program to find the perfect number using a while loop.
Example 3: Find the perfect number between two numbers through a C program.