Project Euler #2: Even Fibonacci numbers

Sort by

recency

|

639 Discussions

|

  • + 0 comments

    import math import os import random import re import sys

    def even_fib_sum(n): a, b = 1, 2 total = 0 while b <= n: if b % 2 == 0: total += b a, b = b, a + b return total

    if name == 'main': t = int(input().strip()) for t_itr in range(t): n = int(input().strip()) print(even_fib_sum(n))

  • + 0 comments

    def fibnacci(n): total = 0 f0, f1 = 0, 1 while f0 <= n: if f0 % 2 == 0: total += f0 f0, f1 = f1, f0 + f1 return total

  • + 0 comments

    visit site

    defining a function to check the given condition
    def sum_fib(n): a,b= 1,2 even_sum = 0 while b<=n: if b%2==0: even_sum +=b a,b=b,a+b return even_sum
    
    if name == 'main': t = int(input().strip())
    
    for t_itr in range(t):
        n = int(input().strip())
        res = sum_fib(n)
        print(res)
    
  • + 0 comments

    Haskell

    import Control.Applicative
    import Control.Monad
    import System.IO
    
    all_fibs = 1 : 2 : zipWith (+) fibs (tail fibs)
    fibs =  take 100 all_fibs 
    
    reduce :: [Int] -> [Int]
    reduce xs = filter (\n -> n `mod` 2 == 0) xs
    
    cutoff :: Int -> [Int] -> [Int]
    cutoff n xs = filter (\m -> m <= n && m > 0) xs
                     
    main :: IO()
    main = do
        t_temp <- getLine
        let t = read t_temp :: Int
        forM_ [1..t] $ \a0  -> do
            n_temp <- getLine
            let n = read n_temp :: Int
            
            let cutoff_fibs = cutoff n fibs  
            let even_fibs = reduce cutoff_fibs
            
            let fibSum = sum even_fibs :: Int
            putStrLn (show fibSum)
            
    
  • + 0 comments

    lst=[1,2] t = int(input().strip()) for a0 in range(t): n = int(input().strip()) for i in range(2,n): nextt=lst[i-1]+lst[i-2] if nextt>n: break else: lst.append(nextt) e=[j for j in lst if j%2==0] print(sum(e)) lst=[1,2]