In this C program, we will check whether a number is perfect number or not. A number is a perfect number, if the sum of all the divisors of a number is equal to the number itself.
Algorithm to check a number is perfect number or not
- Take a number N as input from user.
- Find all divisors of a N between 1 to N/2.
- Add the values of all divisors to a variable sum.
- If sum is equal to N, then N is a perfect number otherwise not a perfect number.
C program to check a number is perfect number
#include<stdio.h> int main () { int num, i, divSum; printf("Enter a number\n"); scanf("%d", &num); for (divSum = 0, i = 1; i <= num/2; i++) { if (num % i == 0) { divSum += i; } } /* Check if Divisor sum is equal to input number */ if (divSum == num) printf("%d is a Perfect Number\n", num); else printf("%d is Not a Perfect Number\n", num); return 0; }Output
Enter a number 10 10 is Not a Perfect Number
Enter a number 6 6 is a Perfect Number
Related Topics