DEV Community

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

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

F#, ridiculously short/fast solution

// perfect num calculation is 2^(p-1)*(2^p - 1)
// source: https://oeis.org/A000396
let getPerfect p =
    pown 2L (p - 1) * (pown 2L p - 1L)

Usage

// prime calculation is out of scope for this problem
// (and this few can be looked up easily)
// so I simply list them here.
let mersenneExponents =
    [1; 2; 3; 5; 7; 13; 17; 19; 31]

List.map getPerfect mersenneExponents
|> printfn "%A"
// [1L; 6L; 28L; 496L; 8128L; 33550336L; 8589869056L; 137438691328L; 2305843008139952128L]

This runs in 0.35ms or ~3500 ticks in Release mode (after a JIT prerun). It basically turns the problem around to be just a matter of inputting Mersenne Exponents. Not many are needed before overflowing traditional memory structures like int64.