Skip to content

Project Euler Problem 1

September 27, 2011

Despite late night I cannot resist attempt to post some code. Problem 1 is rather trivial. Can be solved by generating sought items via list comprehensions like below

printfn "Problem 1 Answer: %d" (
    List.sum [3..3..999]
    + List.sum [5..5..999]
    - List.sum [15..15..999])

or by generating list of potential items and then filtering by target property

let inline (%%) x y = x % y = 0

[for x in 1..999 do if x %% 3 || x %% 5 then yield x]
|> List.sum
|> printfn "Problem 1 Answer: %d"

or by generating ONLY required items, excluding duplicates and folding sum

[3..3..999] @ [5..5..999]
|> set
|> Set.fold (+) 0
|> printfn "Problem 1 Answer: %d"

or even building a higher-order function for recognizing multiples of 3 or 5,then filtering a sequence of natural numbers thru this function, taking only those that less, than 1000, and finally getting their sum

let inline multipleOf y x = x % y = 0
let multipleOf3, multipleOf5 = multipleOf 3, multipleOf 5
let multipleOf3Or5 = (fun x -> multipleOf3 x || multipleOf5 x)

let problem001 () =
    Seq.initInfinite id
    |> Seq.takeWhile ((>) 1000)
    |> Seq.filter multipleOf3Or5
    |> Seq.sum

Despite verbosity I personally like the last one the most as it LITERALLY follows the challenge description, no more no less:

  1. of all natural numbers take those less, than 1000
  2. of these take just multiples of 3 or 5
  3. of these find their sum
Advertisements

From → Project Euler

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: