Why isn't this simple program working?

This is a relatively simple program thats supposed to list all the perfect numbers up to 500, along with the count next to each number. But for some reason its not working.

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
 #include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int i, n;
    int sum = 0;
    int cnt = 0;



for(int i=0; i<=500; i++){
    for(int n = 1; n<i; n++){
            if (i%n==0)
                sum+=n;}
                if (sum==i)
                    {cnt++;
                    cout << cnt << "\t" << i << endl;
                    }
}

return 0;

}


Whats wrong with it?
for(int i=0;i<=500;i++)

should be

for(i=0;i<=500;i++)

u declared i many times.....
Last edited on
Nope, doesn't make a difference. I removed the int for n also. Still not working.
I posted a post here before and was being a dumball because I didn't see that you actually did describe what the program was doing in your post.

My apologies! Looking at program now.

EDIT:

You'll have to reset your sum to zero when you start to check a new number.
Last edited on
You'll have to reset your sum to zero when you start to check a new number.


Did that. Still not working. See below

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
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int i, n;
    int sum = 0;
    int cnt = 0;



for(i=0; i<=500; i++){
    for(n = 1; n<i; n++){
            if (i%n==0)
                sum+=n;}
                if (sum==i)
                    {cnt++;
                    cout << cnt << "\t" << i << endl;
                    sum = 0;
                    }

}
return 0;

}
That does not reset the sum between numbers, only resets it when you find a perfect number.

Resetting sum to zero should probably be done between lines 14 and 15 -- since that's where you start testing each number.
Last edited on
Thank you so much it worked.

Previously I had set the sum to 0 within the brazes of the if statement. i just had to move it outside of the braces to separate it from the if-statement. My finalized, working program below:

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
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    int i, n;
    int sum = 0;
    int cnt = 0;



for(i=0; i<=500; i++){
    for(n = 1; n<i; n++){
            if (i%n==0)
                sum+=n;}
                if (sum==i)
                    {cnt++;
                    cout << cnt << "\t" << i << endl;
                    }

sum=0;

}

}

make sure to hit solved button! good job!
Topic archived. No new replies allowed.