This C++ program is used to find the perfect number of a positive number and find its all positive divisors excluding that number.
For example: 6 is Perfect Number since divisor of 6 are 1, 2 and 3. Sum of its divisor is
1 + 2+ 3 =6
and 28 is also a Perfect Number
since 1+ 2 + 4 + 7 + 14= 28
Other perfect numbers: 496, 8128
Example:
#include <iostream>
#include <cctype>
using namespace std;
int main(){
int n,i=1,sum=0;
cout << "Enter a number: ";
cin >> n;
while(i<n){
if(n%i==0)
sum=sum+i;
i++;
}
if(sum==n)
cout << i << " is a perfect number\n";
else
cout << i << " is not a perfect number\n";
system("pause");
return 0;
}
Program Output:
6 is a perfect number 15 is not a perfect number 28 is a perfect number 496 is a perfect number
Explanation:
For Example, 6 is a perfect number since divisors of 6 are 1, 2, and 3, then sum of its divisor is 1 + 2 + 3 = 6. So, first of all, you have to include the iostream header file using the "include" preceding by # which tells that hat the header file needs to be process before compilation, hence named preprocessor directive. Again the ctype header file declares several functions which are helpful for testing and mapping characters. Now, for removing naming conflict you can use namespace statement within a program.
Now, the main() function is declared having return type as integer. Now you have to declare three integer type variables name - 'n', 'i' and sum and initialize 'i' as 1 and sum as 0. Now use the cout statement to display a message:
"Enter a number: ".
Then, the cin statement will fetch the value from the keyboard and initializes it to 'n'. Now you will implement a while loop which will check for iteration whether 'i' is greater than 'n' or not. If yes, then check whether n%i is equals to 0; If the for statement results as True, sum becomes sum+I and I gets incremented by 1. Now, outside the loop, it is checked when sum==n, prints "The given number is a perfect number" else not.