fork download
  1. open System
  2. open System.Collections.Generic
  3.  
  4. let isPrime n =
  5. List.exists (fun i -> n % i = 0) [2..(n - 1)]
  6.  
  7. let recip =
  8. let cache = Dictionary<_, _>()
  9. fun n m ->
  10. assert (isPrime m)
  11. if cache.ContainsKey( (n, m) ) then cache.[ (n, m) ]
  12. else
  13. let res = List.find (fun a -> n * a % m = 1) [1..(m - 1)]
  14. cache.[ (n, m) ] <- res
  15. res
  16.  
  17. let rec binomialMod n k m =
  18. let rec recBinomialMod n k m result =
  19. if k = 1 then n * result % m
  20. else
  21. let k_1 = recip k m
  22. recBinomialMod (n - 1) (k - 1) m (result * n * k_1 % m)
  23. recBinomialMod n k m 1
  24.  
  25. let primes = List.filter isPrime [1000..5000]
  26. let binomials = List.map (fun m -> binomialMod (int (1000000000000L % (int64 m))) 1000000000 m) primes
  27.  
  28. let solution =
  29. let rec recSolution (binomials:(int list)) product chosen =
  30. seq {
  31. if chosen = 3 then yield product
  32. else if binomials.IsEmpty then yield 0
  33. else
  34. yield! recSolution binomials.Tail product chosen
  35. yield! recSolution binomials.Tail (product * binomials.Head) (chosen + 1)
  36. }
  37. (Seq.sum (recSolution binomials 1 0))
  38.  
  39. Console.WriteLine solution
Runtime error #stdin #stdout 2.59s 16056KB
stdin
1
2
10
42
11
stdout
Standard output is empty