0

I am working on a problem where I must show all perfect integers between 1 and 1000, as well as the divisors to get them. I can get the integers just fine with this code:

#include <iostream>

using namespace std;
void Perfect(int);

int main() {
          for (int i = 1; i < 1000; i++) {
          Perfect(i);
                     }
system("pause");
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;
                     }
}

But I can't figure out where to put things in to get each divisor for each number. It needs to show up like this:

28 = 1 + 2 + 4 + 7 + 14

Any ideas for how to do that? Thanks

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Ancient Dragon
0

try this:

void Perfect (int number) 
{
    int sum = 0;
    vector<int> ay;
    for (int i = 1; i < number; i++) 
    {
        if (number % i == 0) 
        {
            sum = sum + i;
            ay.push_back(i);
        }
    }
    if (sum == number) 
    {
        size_t i = 0;
        cout << sum << " = ";
        for(i = 0; i < ay.size()-1; i++)
        {
            cout << ay[i] << " + ";
        }
        cout << ay[i] << "\n";
    }
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.