Skip to content

Instantly share code, notes, and snippets.

@onlyleft
Last active August 29, 2015 14:05
Show Gist options
  • Select an option

  • Save onlyleft/948b097698f431c89beb to your computer and use it in GitHub Desktop.

Select an option

Save onlyleft/948b097698f431c89beb to your computer and use it in GitHub Desktop.
Learning Haskell with Project Euler - Problem 2 (Fibonacci Sequence Sum with Limit)
-- Base formula, but this is exponential time
fib :: Int -> Int
fib 0 = 0
fib 1 = 1
fib x
| x < 0 = error "No Negatives allowed"
| otherwise = fib (x-2) + fib (x-1)
-- When doing an unbounded sequence, where should we stop?
fibLimit:: Int -> Int -> Int
fibLimit limit number
| limit <= 0 = error "Really?"
| number <= 0 = 0
| fib number < limit = fibLimit limit (number+1)
| otherwise = number-1
main = do
let maxFib = fibLimit 4000000 20
print (sum [fib x | x <- [1..maxFib]])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment