I was exploring Jupyter notebooks , that combines live code, markdown and data, through Microsoft's implementation, known as MS Azure Notebooks , putting together a small library of R and F# notebooks . As Microsoft's FAQ for the service describes it as : ...a multi-lingual REPL on steroids. This is a free service that provides Jupyter notebooks along with supporting packages for R, Python and F# as a service. This means you can just login and get going since no installation/setup is necessary. Typical usage includes schools/instruction, giving webinars, learning languages, sharing ideas, etc. Feel free to clone and comment... In R Azure Workbook for R - Memoisation and Vectorization Charting Correlation Matrices in R In F# Charnownes Constant in FSharp.ipynb Project Euler - Problems 18 and 67 - FSharp using Dynamic Programming
Description
Problem #2 is to find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
General Order
- calculate Fibonacci series up to 4MM
- filter list for evens
- sum filtered list
Solution (Improved)
The fundamental improvement is a updated Fibonacci series function, rewritten as a tail-recursion.
let rec fibsRec a b max arr =
if a + b > max then
arr
else
let current = a + b
let newArr = List.append arr [current]
fibsRec b current max newArr
let evenArray = (1::2::(fibsRec 1 2 4000000 [])) |> List.filter (fun x -> x % 2 = 0) |> List.sum
Solution (Original)
//fibonacci via recursion
let rec fibsRec a b max =
if a + b < max then
let current = a + b
let rest = fibsRec b current max
current :: rest
else
[]
//generate list with 1, 2 and all other larger fibonaccis
let fibs = 1::2::(fibsRec 1 2 4000000)
//filter for even only
let evenArray = fibs |> List.filter (fun x -> x % 2 = 0)
//sum evens
let sumArray = List.sum evenArray
Comments
Post a Comment