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

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