Cover Image for Perfect Number Program in C
88 views

Perfect Number Program in C

A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). For example, the number 28 is a perfect number because its proper divisors are 1, 2, 4, 7, and the sum of these divisors is 1 + 2 + 4 + 7 = 14, which is equal to 28.

Here’s a C program to check if a given number is a perfect number:

C
#include <stdio.h>

int main() {
    int num, sum = 0;

    printf("Enter a positive integer: ");
    scanf("%d", &num);

    if (num <= 0) {
        printf("Please enter a positive integer.\n");
    } else {
        // Find the sum of proper divisors
        for (int i = 1; i <= num / 2; i++) {
            if (num % i == 0) {
                sum += i;
            }
        }

        // Check if it's a perfect number
        if (sum == num) {
            printf("%d is a perfect number.\n", num);
        } else {
            printf("%d is not a perfect number.\n", num);
        }
    }

    return 0;
}

In this program:

  • We prompt the user to enter a positive integer.
  • We check if the entered number is less than or equal to 0. If it is not positive, we display an error message.
  • If the input is a positive integer, we calculate the sum of its proper divisors by iterating through numbers from 1 to num / 2 and checking if they are divisors of num.
  • We then compare the calculated sum with the original number to determine whether it’s a perfect number or not.

Compile and run the program, and it will check if the entered number is a perfect number and provide the corresponding output.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS