Write a C++ Program to Check Perfect Number with an example. Any number can be perfect if the sum of its divisors (excluding the actual number) equal to the number. For instance, 6 is divisible by 1, 2, 3 (excluding 6) and the sum of 1 + 2 + 3 = 6. So, 6 is a perfect number.
In this C++ perfect number example, we used for loop (for(i = 1 ; i < number ; i++)) to iterate from 1 to number. We used the if condition (if(number % i == 0)) to check whether the number divisible by loop value equals 0. If true, add that value to the sum. Finally, we used the If condition (if(number == sum)) to check whether the number equal to the sum and print the result.
#include<iostream>
using namespace std;
int main()
{
int number, i, sum = 0;
cout << "Please Enter the Number to check for Perfect = ";
cin >> number;
for(i = 1 ; i < number ; i++)
{
if(number % i == 0)
{
sum = sum + i;
}
}
if(number == sum)
{
cout << number << " is a Perfect Number";
}
else
{
cout << number << " is Not a Perfect Number";
}
return 0;
}
C++ Program to Check Perfect Number using a While loop
#include<iostream>
using namespace std;
int main()
{
int number, i = 1, sum = 0;
cout << "Please Enter the Number to check for Perfect = ";
cin >> number;
while( i < number )
{
if(number % i == 0)
{
sum = sum + i;
}
i++;
}
if(number == sum)
{
cout << number << " is a Perfect Number";
}
else
{
cout << number << " is Not a Perfect Number";
}
return 0;
}
C++ Program to print Perfect Numbers from 1 to N
This C++ perfect number example allows the user to enter the minimum and maximum values. Next, it prints the perfect numbers between min and max value.
#include<iostream>
using namespace std;
int main()
{
int minimum, maximum, number, i, sum;
cout << "Enter Minimum and Maximum to find Perfect Numebrs = ";
cin >> minimum >> maximum;
cout << "\nPerfect Numbers Between " << minimum << " and " << maximum << " = ";
for(number = minimum; number <= maximum; number++)
{
for(i = 1, sum = 0; i < number ; i++)
{
if(number % i == 0)
{
sum = sum + i;
}
}
if(number == sum)
{
cout << number << " ";
}
}
return 0;
}