# 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:-

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:-

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.

#### Amit Rawat

#### Latest posts by Amit Rawat (see all)

- Python Program to Display or Print Prime Numbers Between a Range or an Interval - June 18, 2019
- Python Program To Print Pascal’s Triangle (2 Ways) - June 17, 2019
- Python program to print Floyd’s Triangle (3 Ways) - June 15, 2019