We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
#!/bin/python3importsyst=int(input().strip())fora0inrange(t):n=int(input().strip())deffibonaci(n):ifn==1:return1ifn<=0:return0a,b=0,1# Defining the 1st and 2nd position values of the Fibonacci seriesans=0whileTrue:# Creating a loop to update the values of a and b so that we can check if the next value is even or notifa%2==0:# Considering a to always be the first value and checking if it is even or notans+=a# If the value stored in a is even, add it to the resulta,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)ifa>n:# Check if the value of a exceeds the given n, and if so, break the loopbreakprint(ans)# Output the final answerfibonaci(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.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #2: Even Fibonacci numbers
You are viewing a single comment's thread. Return to all comments →
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.