Perfect Numbers Program in C
C program to check a given number as a perfect number.
C program to check a given number as a perfect number.
Write a program to check whether a given number is a perfect number.
Input:
6
Output:
6 is a perfect number.
Explanation:
A perfect number is a positive integer which is equal to the sum of its positive divisors, excluding itself.
The positive divisors of 6 are 1, 2 and 3.
Sum = 1 + 2 + 3 = 6.
Hence, 6 is a perfect number.
Input:
12
Output:
12 is not a perfect number.
Input:
1
Output:
1 is not a perfect number.
Explanation:
1 is not a perfect number because the only divisor of 1 is 1 itself. According to the definition, a perfect number is a positive integer which is equal to the sum of its positive divisors, excluding itself. So, clearly 1 is not a perfect number.
You need to write the complete program using the following template as the starter:
#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
// Write your code here
return 0;
}
Copy and paste the above code in your favorite IDE and start writing your code after the comment “// Write your code here.”
Pro tip: First, try writing the code on your own. Try every possible thing you can to come up with the solution. If you still can’t figure it out, then check the solution and see what went wrong. This is how you learn. 🙂
To verify the program you have written, go ahead and test your program using the following test cases:
Input | Output | |
---|---|---|
Test Case 1 | 28 | 28 is a perfect number. |
Test Case 2 | 12 | 12 is not a perfect number. |
Test Case 3 | 496 | 496 is a perfect number. |
Test Case 4 | 1 | 1 is not a perfect number. |
Don’t forget to try the code on your own before diving into the solution.
We can use either for loop or while loop to solve this problem.
// Program to check whether a given number is a perfect number using for loop.
#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
// Write your code here
int sum = 0;
// Iterate from 1 through half of the number
for(int i = 1; i <= n/2; i++) {
// if divisor is found, then add it to the previous sum
if (n % i == 0) {
sum += i;
}
}
if (sum == n)
printf("%d is a perfect number.", n);
else
printf("%d is not a perfect number.", n);
return 0;
}
In the above program:
// Program to check whether a given number is a perfect number using while loop.
#include <stdio.h>
int main() {
int n;
printf("Enter a number: ");
scanf("%d", &n);
// Write your code here
int sum = 0, i = 1;
// Iterate from 1 through half of the number
while(i <= n/2) {
// if divisor is found, then add it to the previous sum
if (n % i == 0) {
sum += i;
}
i++;
}
if (sum == n)
printf("%d is a perfect number.", n);
else
printf("%d is not a perfect number.", n);
return 0;
}
In the above program, the for loop is replaced by the while loop. This does not affect the logic of the program. The logic is the same.
Leave a comment