I have a function that checks Fibonacci numbers for even.
JavaScript
x
10
10
1
def fibonacci(num=4):
2
fib1 = fib2 = 1
3
print(0, end=' ')
4
for i in range(1, num):
5
fib1, fib2 = fib2, fib1 + fib2
6
if (fib2 % 2) == 0:
7
print(fib2, end=' ')
8
9
fibonacci()
10
I need it to output a specified number of even numbers
Example input: 4
Example output: 0 2 8 34
Advertisement
Answer
You could just go over the even ones directly:
JavaScript
1
6
1
def fibonacci(num=4):
2
fib1, fib2 = 1, 0
3
for _ in range(num):
4
print(fib2, end=' ')
5
fib1, fib2 = fib1 + 2*fib2, 2*fib1 + 3*fib2
6
Consider two adjacent Fibonacci numbers a
and b
(initially 1 and 0) and what happens when you shift the window:
JavaScript
1
5
1
a b # odd even
2
b a+b # even odd
3
a+b a+2b # odd odd
4
a+2b 2a+3b # odd even
5
So every third Fibonacci number is even and that last line also tells you how to shift by three steps directly.