Second Function Doesn't Give a Output

Pages: 12
I thought I followed what you were saying but I'm getting a really weird output

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 #include <iostream>
#include <cmath>
using namespace std;

bool isPerfect(int n);
void showPerfect(int n);

int main()
{
    for (int i = 0; i <= 8000; i++)
    {
        if (isPerfect(i)) showPerfect(i);
    }
}

bool isPerfect(int n)
{
    int sum = 0, f;

bool result;

for( f = 1; f <= n/2; f++)
{
  if ( n % f == 0)
  {
      sum += f;
  }
}


if ( sum == n)
{
   result = true;
}

else
{
    result = false;
}

return result;
}
void showPerfect(int n)
{
        int f;
       for( f = 1; f <= n/2; f++)
          {
            if ( n % f == 0)
            {
              cout << f << " + " << f;
            }
            cout << '\n';
          }
}
Ok, I tried to run that - the output is pretty weird!

Firstly, the cout at line 52, is inside the for loop, which means you get lots and lots of newlines being output. Move it down a line or two, so it is outside the loop.

Secondly, line 50 is outputting the same factor twice, with a plus in the middle. Remove the first one,

Then the function looks like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void showPerfect(int n)
{
    int f;
    
    for( f = 1; f <= n/2; f++)
    {
        if ( n % f == 0)
        {
            cout << " + " << f;
//          cout << f << " + " << f;            
        }
//        cout << '\n';
    }

    cout << '\n';
    
}

and this is the output:
 + 1 + 2 + 3
 + 1 + 2 + 4 + 7 + 14
 + 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248

That's heading in the right direction. What can be done to fix it? Well, add cout << n << " = "; at the beginning of the function, before the start of the for-loop.

Now the output is like this:
0 =
6 =  + 1 + 2 + 3
28 =  + 1 + 2 + 4 + 7 + 14
496 =  + 1 + 2 + 4 + 8 + 16 + 31 + 62 + 124 + 248


So what can be done to get rid of the unwanted '+' after the = sign?

There must be several ways to do that. Since we know that the first factor is always 1, that could be included in the initial cout,
cout << n << " = 1";
That seems like a step backwards, the output has changed from
 
6 =  + 1 + 2 + 3
to
 
6 = 1 + 1 + 2 + 3


Now, one more step. Make the for loop start from f = 2 instead of f = 1.

That should do it.

Actually it still leaves a line starting "0 = ". I'm not sure what should be done about that. As far as I can tell, the first perfect number is usually considered to be 6, so you might add statement inside function isPerfect to return false if the input is less than 2. It seems a bit inelegant but I'm not sure of a better way.
Thank you so much, you are a lifesaver.
Topic archived. No new replies allowed.
Pages: 12