Perfect Numbers

Tuesday, July 26, 2011 2 Comments A+ a-

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;
}

The program shows a for loop of range 1 to 1000.

In each loop, it evaluates the number by looking for its factors. And every time a factor is seen, it adds it to the variable sumOfFactors which will contain the sum of the all factors. But it should always have an initial value of 0 so it is initialized before it enters the loop which evaluates for the factors. Notice that this loop is only up to the value of the number less than 1 (j < i) because the number itself should not be part of the summed up factors.   

And a factor is determined if it has no remainder thus modulus operator (%) is used. If there is no remainder then j is a factor of the number ( i ).  

Now after the the loop which sums up all the factors of the number, it checks if that sum is equal to the number and prints it if it is a perfect number. Then the loop continues with the new value of the number until all the numbers from 1 - 1000 are evaluated.

2 comments

Write comments
December 18, 2016 at 5:33 AM delete

Thanks for this post! helped me a lot! :)

Reply
avatar
Abdel Jamal
AUTHOR
April 20, 2017 at 5:09 AM delete

Can you write a program to display
untegers between 1 and 100 that are divisible by either 6 or 7

Reply
avatar