I want to find all perfect numbers from interval x to y. Any help how can I do that ?
Asked
Active
Viewed 1,271 times
1 Answers
3
Here is a simple solution, it's not very fast, just an example to understand how perfect numbers work.
#include <iostream>
using namespace std;
int main()
{
int x, y;
int sum_del;
cin >> x >> y;
for(int i = x; i <= y; i++){
sum_del = 0;
for (int j = 1; j <= i/2; j++){
if (i % j == 0)
sum_del += j;
}
if (sum_del == i)
cout << i << endl;
}
return 0;
}

user2699298
- 1,446
- 3
- 17
- 33
-
1There's also no need to check until i/2, it's enough to go from 2 to sqrt(i). :) – Eutherpy Nov 05 '13 at 17:54
-
thanks, i get it. thanks for the example! – user2943407 Nov 05 '13 at 18:02
-
Actually, the best thing to do would be to skip every second (every odd) number - there's a theorem proving that, if there is an odd perfect number, it has to be greater than 10^300. – Eutherpy Nov 05 '13 at 18:04