ProjectEuler Solved Question-2 (with 3 solutions)

 Q-2:- 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, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.



SOL:-1
  • The fib() generator is responsible for generating Fibonacci numbers
  • filter(lambda n: n % 2 == 0, ...) keeps just the even-valued elements
  • sum(...) adds them up


def fib(max):
    f1, f2 = 0, 1
    while f1 < max:
        yield f1
        f1, f2 = f2, f1 + f2

print(sum(filter(lambda n: n % 2 == 0, fib(4000000))))

SOL:-2sum = 0
f1, f2 = 0, 1
while f2 < 4000000:
    if f2 % 2 == 0:
        sum += f2
    f1, f2 = f2, f1 + f2
print(sum)


SOL:-3
P2 = 0
fib= 0
f1 = 1
f2 = 0
debugP2 = []
while fib < 4000000:
    fib = f1 + f2
    f2 = f1
    f1 = fib
    if fib % 2 == 0:
        P2 += fib
        debugP2.append(fib)
print(debugP2)
print(P2)

Comments

Popular posts from this blog

XAMPP, SQL BASIC COMMANDS

The Minion Game Hackerrank Solution

Arrays - DS | HackerRank Solutions