Okay, I want to start off saying that yes this is a homework assignment but no I don't just want the answer for it. I actually want to learn how to work this. Having said that, I was assigned to determine whether a number is a perfect number and print all the perfect numbers from 1 - 1000. Here's what I have so far. I'm pretty positive that my flaw is in the factoriation loop.

#include <iostream>

using namespace std;

int isPerfect(int number)
{
     int sum = 0;
     int a = 0;
     int factor = 0;

     for(a = 1; a < number; a++)
     {
          if(number % a == 0) /* gets factorization */
               factor = a;        
     }

     sum = sum + factor;

     if(sum == number)
          cout << number << " is a perfect number" << endl;
}      

int main()
{
     int number = 0; /* number used for everything */
     int i = 0; /*for loop variable */  

     for(i = 1; i < 1001; i++)
     {
          number = i;
          isPerfect(number);
     }            

     cout << endl << endl;
     system("pause");
} 

Recommended Answers

All 5 Replies

Line 17 needs to be inside your if statement in your for loop. The way you have it now it will only add the last factor that you find.

I had tried that but at this point, it still doesn't return any perfect numbers.

From the Wikipedia:

n number theory, a perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself (also known as its aliquot sum). Equivalently, a perfect number is a number that is half the sum of all of its positive divisors (including itself) i.e. σ1(n) = 2n.

First, express the math as pseudo-code, then write code that expresses that in concrete terms. So, first show us the pseudo-code.

IE: sum(div(x)) = x, and (sum(div(x) + x)/2 = x.

Obviously, the factorization of x is the key. I'm not 100% sure, but that may mean prime factors of x.

but that may mean prime factors of x.

Not necessarily prime factors.

Read this.

28 is a perfect number because 1 + 2 + 4 + 7 + 14 = 28.

Try this.

for( a = 1; a < (number/2)+1 ; a++)
{

   if(number % a == 0)
   {
      /* gets factorization */
      sum = sum + a;
   }

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.