DEV Community

Discussion on: Write a script to find "Perfect Numbers"

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

Runtime is about 40 seconds in Release mode. The largest cost is finding divisors. I used the least expensive algorithm I could find. But it is still expensive. So to get the runtime down that low, I optimize down the number of inputs using nektro’s observation.

Thread Thread
 
gmartigny profile image
Guillaume Martigny • Edited

You could gain a little by only generating prime numbers for your candidates. Eratosthenes' sieve is not that hard to implement.

Thread Thread
 
kspeakman profile image
Kasey Speakman

I will post another solution using primes. Thanks for the tip!

Thread Thread
 
kspeakman profile image
Kasey Speakman • Edited

I posted the prime-based solution here. The actual perfect number calculation time is now negligible, and the code can be a one-liner. But it requires being fed Mersenne Exponents. Fortunately, very few/small Mersenne Exponents quickly turn into perfect numbers which are too large for traditional memory structures.