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

Recommended Answers

All 11 Replies

Member Avatar for iamthwee

Which part are you stuck on?

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.

Member Avatar for iamthwee

I'm not sure, are there four perfect numbers between 1 and 1000?

Sorry, it's three. 6, 28, and 496

Member Avatar for iamthwee

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

}

commented: :) +0

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?

Member Avatar for iamthwee

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.

Member Avatar for iamthwee

good luck!

hi i want same program, but in middle of [2, N]. thnks a lot.

#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();
 }
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.