You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
992 B
Forth

open System
let factorsWithMolteplicity n =
let rec loop c p =
if c < (p * p) then [c]
elif c % p = 0 then p :: (loop (c/p) p)
else loop c (p + 1)
loop n 2
|> List.countBy id
let isPerfect n =
let sumDiv k =
k
|> factorsWithMolteplicity
|> List.map (fun (p,m) -> ((pown p (m+1))-1)/(p-1))
|> List.fold (*) 1
sumDiv n = 2*n
// brute-force approach
let divisors n =
[1..n/2]
|> Seq.filter (fun f -> n % f = 0)
let sumProperDivisors n =
n
|> divisors
|> Seq.sum
// perfect
let isPerfect2 n = (sumProperDivisors n = n)
let timer = new System.Diagnostics.Stopwatch()
timer.Start()
printfn "%A" (isPerfect 8128)
timer.Stop()
printfn "%f" timer.Elapsed.TotalMilliseconds
printfn "Elapsed Time: %i" timer.ElapsedMilliseconds
let timer2 = new System.Diagnostics.Stopwatch()
timer2.Start()
printfn "%A" (isPerfect2 8128)
timer2.Stop()
printfn "%f" timer2.Elapsed.TotalMilliseconds
printfn "Elapsed Time: %i" timer2.ElapsedMilliseconds