Fibonacci numbers in F#
Posted
by BobPalmer
on Geeks with Blogs
See other posts from Geeks with Blogs
or by BobPalmer
Published on Sat, 03 Apr 2010 17:27:08 GMT
Indexed on
2010/04/03
23:43 UTC
Read the original article
Hit count: 505
As you may have gathered from some of my previous posts, I've been spending some quality time at Project Euler. Normally I do my solutions in C#, but since I have also started learning F#, it only made sense to switch over to F# to get my math coding fix.
let rec fib n1 n2 c =
if c = 1 then
n2
else
fib n2 (n1+n2) (c-1);;
let GetFib num =
(fib 1 1 num);;
printfn "%A" (GetFib 1000);;
Essentially, this function works through the sequence moving forward, passing the two most recent numbers and a counter to the recursive calls until it has achieved the desired number of iterations. At that point, it returns the latest fibonacci number.
Enjoy!
© Geeks with Blogs or respective owner