mirror of
https://github.com/correl/euler.git
synced 2024-11-23 19:19:53 +00:00
Haskell 002
This commit is contained in:
parent
25798c7cc2
commit
c1dc6c41b9
1 changed files with 27 additions and 0 deletions
27
haskell/e002.hs
Normal file
27
haskell/e002.hs
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
{-
|
||||||
|
Find the sum of all the even-valued terms in the Fibonacci sequence which do not exceed four million.
|
||||||
|
|
||||||
|
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
|
||||||
|
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
|
||||||
|
Find the sum of all the even-valued terms in the sequence which do not exceed four million.
|
||||||
|
-}
|
||||||
|
|
||||||
|
import Text.Printf
|
||||||
|
|
||||||
|
fib :: (Integral a) => (a, a) -> a
|
||||||
|
fib (x, y) = x + y
|
||||||
|
|
||||||
|
fibnext :: (Integral a) => (a, a) -> (a, a)
|
||||||
|
fibnext (x, y) = (y, x + y)
|
||||||
|
|
||||||
|
fibsumeven :: (Integral a) => a -> a
|
||||||
|
fibsumeven max = fibsumeven_ max 0 (0,1)
|
||||||
|
|
||||||
|
fibsumeven_ :: (Integral a) => a -> a -> (a, a) -> a
|
||||||
|
fibsumeven_ max total pair
|
||||||
|
| fib pair > max = total
|
||||||
|
| even (fib pair) = fibsumeven_ max (total + (fib pair)) (fibnext pair)
|
||||||
|
| otherwise = fibsumeven_ max total (fibnext pair)
|
||||||
|
|
||||||
|
main = do
|
||||||
|
printf "Sum of even fibonacci terms <= 4,000,000: %d\n" (fibsumeven 4000000 :: Int)
|
Loading…
Reference in a new issue