I am trying to write a C++ program that will list the perfect numbers between 1 and 1000. I also have to print the divisors to confirm the number is perfect. I started by trying to find the perfect numbers. Here is my code. Please help.

#include <iostream>

using std::cout;


int Perfect (int number)
{
int sum = 0;

for (int i = 1; i <= number; i++)
{

if (number % i == 0)
{
sum = sum + i;
}
}
if (sum == number)
{
cout<<sum<<" is a perfect number";
}
return 0;
}

int main()
{
for (int i = 1; i <= 1000; i++)
{
Perfect(i);
}
return 0;
}

The program compiles with no errors but when i run the program, the result I get is
1 is a perfect number.

I'm not sure what I did wrong because I'm not getting any errors. I think I should get at least four numbers between 1 and 1000 that are perfect numbers.

#include <iostream>

using namespace std;
void Perfect(int);

int main()
{
for(int i = 1; i <=1000; i++)
{
Perfect(i);
}

std::cin.get();
return 0;
}


void Perfect (int number)
{
int sum = 0;

for (int i = 1; i < number; i++)
{

if (number % i == 0)
{
sum = sum + i;
}
}
if (sum == number)
{
cout << sum<<endl;
}

}

Comments
:)

I noticed the changes you made but I don't understand them. The function for perfect was changed from integer to void and you added cin.get(). What's the purpose of the cin.get() and does changing the function from integer to void mean it doesn't return a value?

Yes, but the main part that you missed was I changed

for (int i = 1; i < number; i++)

Remember, 6 is divisible exactly by : 1, 2,3,and 6

but a perfect number ignore the 6 and just takes the sum of 1,2,3

Changing the for loop from <= to <makes the difference.

Please mark the thread as solved if you are happy

Thank you so much. This problem has now been solved. Changing the <= to < made the program work. Now I just have to add the code to print the divisors.

#include<iostream.h>
#include<conio.h>
void main()
{
 clrscr();

 int n = 9000,sum = 0;
    cout << "list of perfect numbers less than 9000..." << endl;
    for(int num = 1; num <= n; num++)
    {
    sum = 0;
    for(int i = 1; i < num; i++)
    {
       if(!(num%i))
       {
          sum+=i;
       }
    }
    if(sum == num)
        cout <<  num << " Is perfect number" << endl;
    }
    getch();
 }

Edited 3 Years Ago by Reverend Jim: Fixed formatting

This question has already been answered. Start a new discussion instead.