In this article, you will learn how to write a Perfect Number Progam in C Programming Language. There are many methods to determine a perfect number in C, and we will go through each method and explain how it works.
A perfect number is a positive integer equal to the sum of its divisors but not the number itself.
Below is a program to determine if a given number is perfect or not. The idea behind the concept is to loop from 1 to the entered number, then find all the divisors for that number using the modulus operator. Then we sum up all the devisors and check if they are equal to the entered number.
#include <stdio.h> int main () { int number, sum; printf ("Please enter a number \n"); scanf ("%d", &number); sum = 0; for (int i = 1; i < number; i++) { if (number % i == 0) sum = sum + i; } if (sum == number) { printf ("%d is a Perfect Number", number); } else { printf ("%d is not the Perfect Number", number); } }
Output
Please enter a number 28 28 is a Perfect Number
Below is another way to find a perfect number in C using the recursive method.
#include <stdio.h> int PerfectNumber (int number, int sum, int start) { if (number % start == 0 && start < number) { sum = sum + start; } if (start < number) { start++; PerfectNumber (number, sum, start); } else if (start == number) { return sum; } } int main () { int number; printf ("Please enter a number\n"); scanf ("%d", &number); int i, sum = 0, start = 1; sum = PerfectNumber (number, sum, start); if (sum == number) { printf ("\n%d is Perfect Number", number); } else { printf ("\n%d is not a Perfect Number", number); } }
Output
Please enter a number 30 30 is not a Perfect Number
Now, let’s say you want to find all perfect numbers between 1 and 1000. The program below will ask you for the max number, in this case, 1000, and return all perfect numbers between 1 and 1000.
#include <stdio.h> int main () { int maxNumber, sum; printf ("Please enter a max Number \n"); scanf ("%d", &maxNumber); for (int number = 1; number <= maxNumber; number++) { sum = 0; for (int i = 1; i <= number / 2; i++) { if (number % i == 0) { sum += i; } } if (sum == number) { printf ("%d is a Perfect Number\n", number); } } return 0; }
Output
Please enter a max Number 1000 6 is a Perfect Number 28 is a Perfect Number 496 is a Perfect Number