Created
August 22, 2010 23:08
-
-
Save psfblair/544397 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #light | |
| (* If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. | |
| The sum of these multiples is 23. | |
| Find the sum of all the multiples of 3 or 5 below 1000. *) | |
| (* Easiest way: Use a set *) | |
| let multiples = new Set<int>([0..3..1000] @ [0..5..1000]) | |
| let answer = Set.fold (+) 0 multiples | |
| (* More compact *) | |
| let answer = Set.fold (+) 0 (new Set<int>([0..3..1000] @ [0..5..1000])) | |
| (* More efficient *) | |
| let multiplesOf3ButNot5 = [for x in [0..3..1000] do | |
| if x % 5 <> 0 then yield x] | |
| let sumOfList x = List.fold (+) 0 x | |
| let answer = sumOfList(multiplesOf3ButNot5) + sumOfList([0..5..995]) (* What, no exclusive range? *) | |
| (* Lazy sequence *) | |
| let multiples = seq { for x in 0 | |
| |> Seq.unfold( fun(x) -> Some(x, x+1)) do | |
| if x % 3 = 0 || x % 5 = 0 then yield x } | |
| let answer = Seq.takeWhile (fun(x) -> x < 1000) multiples |> Seq.fold (+) 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment