Showing posts with label Perfect Numbers. Show all posts
Showing posts with label Perfect Numbers. Show all posts

Perfect Numbers

C++ program to find Perfect Numbers between 1 to 1000


This program prints all the perfect numbers from 1 to 1000. Perfect numbers are those numbers in which the sum of the number's proper positive factors (excluding the number itself) is equal to that number.
Let's take the number 6 for example having the factors 1,2,3 and adding these factors will equate to the number itself (1+2+3 = 6).

/*
Perfect Numbers
show perfect numbers from 1-1000
*/

#include <iostream>

using namespace std;

int main(void)
{ 
 //variables
 int i,j,sumOfFactors;

 cout << "These are the perfect numbers:" << endl;

 //check numbers from 1-1000
 for (i = 1; i <= 1000; i++)
 {
  sumOfFactors = 0;

  //look for the factors of a number
  for (j = 1; j < i; j++)
  {
   //check for factors and add them up
   if (0 == (i%j))
   {
    sumOfFactors += j;
   }
  }

  //if perfect number, print
  if (sumOfFactors == i)
  {
   cout << i << endl;
  }
 }
   
 getchar();

 return 0;
}