C++ perfect number program

/*program to check whether a number is perfect
or not. Perfect numbers are those whose factors
sum is equal to the number itself e.g 6 and 28 are perfect
factorsSum   1+2+3=6    1+2+4+7+14=28  */

#include <iostream>
using namespace std;

 //function to find perfect number
void perfectNum(int x)
{
   int factorSum=0;
   for(int i=1;i<x;i++)
   {
      if(x%i==0)
      {
      //nested if to print factors 1+2+4....
       if(i==1)
       {
          cout<<"\n"<<i;
          factorSum=factorSum+i;
       }
       else
       {
          cout<<"+"<<i;
          factorSum=factorSum+i;
       }
      }

   }
   if(factorSum==x)
   {
      cout<<"="<<x;
      cout<<"\n\nThe number "<<x<<" is perfect\n";
   }
   else
   {
      cout<<" not = "<<x;
      cout<<"\n\nThe number "<<x<<" is not perfect"<<endl;
   }
}

int main()
 {
    int num;;
    cout<<"Enter a number ";
    cin>>num;
    perfectNum(num);

 return 0;
}

No comments:

Post a Comment