Home > front end >  How to display even Fibonacci numbers by specifying their number?
How to display even Fibonacci numbers by specifying their number?

Time:02-13

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

CodePudding user response:

You could make your fibonacci function a generator that only yields even Fibonacci numbers, and then just pull the desired number of values from it:

def even_fibonacci():
    fib1, fib2 = 0, 1
    while True:
        if fib1 % 2 == 0:
            yield fib1
        fib1, fib2 = fib2, fib1   fib2


it = even_fibonacci()
for _ in range(4):
    print(next(it))

prints:

0
2
8
34

CodePudding user response:

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.

CodePudding user response:

Use while loop instead.

def fibonacci(count=4):
    fib1 = fib2 = 1
    i = 1
    print(0, end=' ')
    while i < count:
        fib1, fib2 = fib2, fib1   fib2
        if (fib2 % 2) == 0:
            print(fib2, end=' ')
            i  =1

fibonacci()

Output: 0 2 8 34

  • Related