Project Euler #2: Even Fibonacci numbers

  • + 0 comments
    #!/bin/python3
    
    import sys
    
    t = int(input().strip())
    for a0 in range(t):
        n = int(input().strip())
        def fibonaci(n):
            if n == 1:
                return 1
            if n <= 0:
                return 0
            a, b = 0, 1  # Defining the 1st and 2nd position values of the Fibonacci series
            ans = 0
            while True:  # Creating a loop to update the values of a and b so that we can check if the next value is even or not
                if a % 2 == 0:  # Considering a to always be the first value and checking if it is even or not
                    ans += a  # If the value stored in a is even, add it to the result
                a, b = b, a + b  # Swap the values: set a to b and b to the sum of a and b as per the Fibonacci series (e.g., 0 1 1 2 3 5 8 -> a=0 b=1 -> step 2 a=1 b=1 -> step 3 a=1 b=2 and so on)
                if a > n:  # Check if the value of a exceeds the given n, and if so, break the loop
                    break
            print(ans)  # Output the final answer
        fibonaci(n)
    

    For the sake of discussion and explanation of the question, I am providing detailed comments within the code. Please refer to these comments for a clear understanding of the logic and functionality of the code.