'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 1:[1]
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
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ka-Wa Yip |
