C++ Program to Check if a Number is a Perfect Number (2 Ways)

In this program, we will learn how to check if a number is a Perfect number or not using the C++ programming language.

What is a Perfect Number?

It’s a number which has the sum of all its positive divisors excluding the number itself equal to the number.
For example:     6
Sum of divisors = 1+2+3 = 6

We will discuss two ways to write code for it.

  • Simple way
  • Optimized way

C++ Programming Code to Check if a Number is a Perfect Number

Simple Way

Code:-

#include<iostream>

using namespace std;

int main (){  
    int i = 1, num, rem, sum=0;

    cout << "Enter the number: ";
    cin >> num;

    while(i < num){
        rem = num % i;
        if (rem == 0)
            sum = sum + i;
        i++;
    }
    if (sum == num)
        cout << num << " is a perfect number." << endl;
    else
        cout << num <<" is not a perfect number." << endl;

    return 0;
}

Output:-

Enter the number: 6
6 is a perfect number.

Optimized Way

Code:-

#include<iostream>
#include<math.h>

using namespace std;

int main (){  
    int i = 2, num, rem, sum=1;

    cout << "Enter the number: ";
    cin >> num;

    while(i <= sqrt(num)){
        rem = num % i;
        if (rem == 0)
            if(pow(i,2) == num)
                sum = sum + i;
            else
                sum = sum + i + num/i;
        i++;
    }
    if (sum == num)
        cout << num << " is a perfect number." << endl;
    else
        cout << num <<" is not a perfect number." << endl;

    return 0;
}

Output:-

Enter the number: 28
28 is a perfect number.

You can learn about many other C++ Programs Here.

Best Books for learning C++ programming language with Data Structure and Algorithms.

The following two tabs change content below.

Amit Rawat

Founder and Developer at SpiderLabWeb
I love to work on new projects and also work on my ideas. My main field of interest is Web Development.

You may also like...