Perfect number

A perfect number is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.

Logic

To check if the number is perfect or not we have to run one loop from 1 to N and sum all the numbers between 1 to N, if the sum is equal to N then it is a perfect number.

Program

#include <iostream>

using namespace std;

int main() {

    int i, num, sum = 0;

    // Take input from user
    cout << "Enter any number : ";
    cin >> num;

    // Calculate sum of all proper divisors
    for(i = 1; i < num; i++) {

        if(num % i == 0) {
            sum += i;
        }
    }

    // Check whether the sum of divisors is equal to num
    if(sum == num) {
        cout << endl << num << " is PERFECT NUMBER";
    }
    else {
        cout << endl << num << " is NOT PERFECT NUMBER";
    }

    return 0;
}

Output

Enter any number : 5
5 is NOT PERFECT NUMBER