Please have a look at the following code
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
using namespace std;
void isPerfect(int);
vector<int> list;
string numList = "";
int main()
{
cout << "Number" << setw(10) << "Divisors" << setw(15) << "Calculation";
for(int i=1;i<=1000;i++)
{
isPerfect(i);
}
}
void isPerfect(int number)
{
int calc = 0;
for(int i=1;i<=(number/2);i++)
{
if(number%i == 0)
{
list.push_back(i);
//numList = numList + string. + ",";
}
}
for(size_t i=0;i<list.size();i++)
{
calc = list[i] + calc;
}
if(calc == number)
{
cout << number << setw(10) << numList << setw(15) << calc << endl;
}
}
In here, I am trying to find the “Perfect Numbers” (perfect numbers – if the sum of it’s divisors, including 1, but not it self, is equal to the number, it is a perfect number. ex 6 )
But in here, everything is correct, but I am not getting any result, rather than printing what I have printed in main method.
Why is this happening? This is not a home work anyway. Please help.
Your list is in a global variable, so it also contains divisors of all previous numbers. Declare it locally in
isPerfect.As you’ll subsequently discover, the same goes for
numList.