Perfect numbers


Write a program to find all the perfect numbers from 1 to 2000. A perfect number is an integer which is equal to the sum of all of its divisors.

example: 1 + 2 + 3 = 6
Do I use a for loop, while loop, or do while loop?
1
2
3
for(int i = 0;i < 2000;i++)
{
}
This is as far as I got. how do I add individual values of a? More specifically,

#include <iostream>
using namespace std;
int main()

{

int a;
for(int a =0; a < 2000; a++)
{
cout << a << endl;
}
Edit: Only click this link if you want a working solution.

http://ideone.com/wbaQYL
Last edited on
Typically, a for loop is for when you know how many times you will loop, and a while loop is for when you don't. A do while is for when you want something to happen at least once.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
for (int i = 0; i < 10; i++)
{
  cout << i '\n';
}

int num;
ifstream myFile("myData.txt");
while ( myFile >> num)
{
  cout << num << '\n'; 
}

char choice;
do
{
  cout "Make a choice, or q to quit: ";
  cin >> choice;
} while (choice != 'q');


Last edited on
Why does this not work?
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


#include <iostream>
using namespace std;

int sumDiv(int x)
{
	int s = 0;
	for ( int s = 1; i < x; ++ 1)
	{
		if(x % i == 0 )
			s += i;

	}
	return s;


}


int main()


{



	for(int i =1; i < 2000; i++)
	{
	int a == sumDiv(i);
	if (a == i)
	cout << i << endl;

	}
}
In sumDiv the for loop should be int i not s.
Topic archived. No new replies allowed.