Sum of Fibonacci numbers

I am new to Haskell. The problem is to find the sum of all even Fibonacci numbers not more than 4 million. I can not use lists.

If I understand correctly, the solution below is erroneous because it uses lists:

my_sum = sum $ filter (odd) $ takeWhile (< 4000000) fibs

Where fibs is a list of all Fibonacci numbers.

Somehow, it’s hard for me not to think in lists in Haskell. Can someone help me solve this problem?

Hi

EDIT:

If anyone is interested, I solved this problem. Here is the code (very awkward, but still working):

findsum threshold = findsum' 0 1 0 threshold


findsum' n1 n2 accu t 
| n2 > t    = accu
| odd n2    = findsum' n2 n3 accu t 
| otherwise = findsum' n2 n3 accu2 t
where
    n3 = n2 + n1
    accu2 = accu + n2
+3
source share
3 answers

excel, . Excel. 1 1 . , . (.. a3 = A1 + A2). "ie, if (mod (a3,2) == 0, a3,0)". . , .

- . .

sumFib :: Integer -> Integer
sumFib threshold = sumFib' 1 1 0 threshold

sumFib' :: Integer -> Integer -> Integer -> Integer -> Integer
sumFib' n1 n2 acc threshold

. , (4 000 000), , . 2 sumFib, . ... , "4613732", ....

n1 - n-1, n2 - n-2.

, .

EDIT: :

sumFib :: Integer -> Integer
sumFib threshold = sumFib' 1 1 0 threshold

sumFib' :: Integer -> Integer -> Integer -> Integer -> Integer
sumFib' n1 n2 acc threshold
     | n1 > threshold = acc
     | otherwise = sumFib' (n2+n1) n1 newAcc threshold
            where newAcc = if n1 `mod` 2 == 0
                               then n1 + acc
                               else acc
+4

, .

BTW, , .

+3

, :

!

1- : - , -F_3 = 2

: + = ; + = ; + = ,

: F_3 + F_6 + F_9 +... + F_ {3k} = 1/2 (F_ {3k + 2} - 1)

: F_3 = 2 = 1/2 (5 - 1) = 1/2 (F_5 - 1)

F_3 + F_6 +... + F_ {3k + 3} = 1/2 (F_ {3k + 2} - 1) + F_ {3k + 3} = 1/2 (F_ {3k + 2} + 2F_ {3k + 3} -1) = 1/2 (F_ {3k + 4} + F_ {3k + 3} -1) = 1/2 (F_ {3k + 5} -1)

3- : 1333333 , 3999999- -.

4- : F_n = 1/sqrt (5) * (phi ^ n - (1-phi) ^ n)

Wikipedia

: F_3 + F_6 +... + F_3999999 = 1/2 (F_4000001 - 1) = 1/2 1/sqrt (5) (phi ^ 4000001 - (1-phi) ^ 4000001) - 1/2 = int (1/2 1/sqrt (5) phi ^ 4000001)

Here int is the integer part. The last step works because -1 <1-phi-0 and therefore (1-phi) ^ 4000001 almost disappears. You can use the calculator to get a numerical value.

+3
source

All Articles