Perfect Numbers (mangled class notes)

I took these notes in class, and mangled them somehow. For the life of me, I can't figure out where the error is. It's meant to find perfect numbers. A perfect number is a number that is the sum of its divisors (minus itself). Thanks for taking a look- I really appreciate it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

int main()
{
	int n,k;
	int sum;
	for(n=2;n<=10000;n++) //we're trying to see if n is perfect.
	{
		sum=0;
		for(k=n/2;k<=n/2;k++)  //if k<=n/2 and sum <=n  
		//also k should start at large end, not low.
		{
			if(n%k==0)
			sum=sum+k;
		if(sum==n)
		cout << n << " is perfect!" << endl;
		}
        }
return 0;
}
This is wrong:
for(k=n/2;k<=n/2;k++)

You're only checking whether n is divisible by n/2.
It should be for (k=2 1;...
Last edited on
In your 2nd loop, k should start at 1, not n/2.
for(k=n/2; k>0; k--)


this test needs to be moved outside the innermost for-loop,
1
2
if (sum==n)
    cout << n << " is perfect!" << endl;

Thank you very much!
Topic archived. No new replies allowed.