C++ program to find perfect number

 Program to find perfect number

A number is said to a perfect number if the sum of the divisor of the number is equal to the given number.
This can be clearly explained using an example
Example:
If the given number is 6
The divisors of 6 are 1, 2, 3
The sum of divisors = 1 + 2 + 3
                                 = 6
As the sum of divisors is equal to original value the number is said to be perfect number

INPUT: 6

OUTPUT: The number is perfect number

Example: 
If the given number is 25
The divisors of 25 are 1, 5
The sum of divisors = 1 + 5
                                = 6
As the sum of divisors is not equal to original value, the number is not a perfect number

INPUT: 25

OUTPUT: The number is not a perfect number

Program:

/*C++ program to find the given number is perfect or not*/

#include <iostream>
using namespace std;
int main ()
{  
    int i, n, div, s=0;
    cout << "Enter a number :  ";
    cin >> n;        //takes the input
    for (i=1; i < n; i++)
    {              //loop to find the perfect number
        div = n % i;
        if (div == 0)
            s = s + i;
    }
    if (s == n)
        cout << "\n" <<" The given number "<<n<<" is a perfect number.";
    else
        cout << "\n" <<" The given number "<<n<<" is not a perfect number.";
    return 0;
}

Output:
Enter a number : 6
The given number 6 is a perfect number.



Initially we include header files required for the program. A namespace is used as additional information to differentiate similar functions, classes, variables etc. with the same name available in different libraries. Using namespace, one can define the context in which names are defined. cout is used to print the given data on the display screen. cin is used to accept the given input. The given input is stored in a variable n. Next we used for loop for iteration purpose, all the values from 1 to n are checked and all the divisors are fined and added together and stored in a variable s. Up-next an if-else loop is used if the given condition is true then if block will get executed and if the condition is not satisfied then else block will be executed. 

Post a Comment

0 Comments