pythonfibonacciparity

How to display even Fibonacci numbers by specifying their number?


I have a function that checks Fibonacci numbers for even.

def fibonacci(num=4):
    fib1 = fib2 = 1
    print(0, end=' ')
    for i in range(1, num):
        fib1, fib2 = fib2, fib1 + fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')

fibonacci()

I need it to output a specified number of even numbers

Example input: 4

Example output: 0 2 8 34


Solution

  • You could just go over the even ones directly:

    def fibonacci(num=4):
        fib1, fib2 = 1, 0
        for _ in range(num):
            print(fib2, end=' ')
            fib1, fib2 = fib1 + 2*fib2, 2*fib1 + 3*fib2
    

    Consider two adjacent Fibonacci numbers a and b (initially 1 and 0) and what happens when you shift the window:

       a     b    # odd even
       b   a+b    # even odd
     a+b  a+2b    # odd odd
    a+2b 2a+3b    # odd even
    

    So every third Fibonacci number is even and that last line also tells you how to shift by three steps directly.