I want to calculate if a number is a perfect number (sum(proper divisors) == number). So all I have to do is get the proper divisors, add them up and look if it's the number. For this I use a for-loop:
cin >> number;
sum = 1;
for (int i = number/2; i > 1; --i) {
if (number % i == 0) {
sum = sum + i;
}
if (sum > number) {break;}
}
if (sum == number) {cout << "perfect!" << endl;}
This loop is too slow. What I have done already as you can see is break out of the loop if the sum is already bigger than the number, I start from higher numbers (so if the sum is greater, it gets there faster), and since 1 is always a proper divisor, I don't need to loop over it.
Now I'm kind of out of ideas and would really appreciate some tips on how to improve this loop further (or even a completely different approach?)
Aucun commentaire:
Enregistrer un commentaire