如何通过指定数字来显示偶数斐波那契数?
How to display even Fibonacci numbers by specifying their number?
我有一个函数可以检查斐波那契数是否为偶数。
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()
我需要它输出指定个数的偶数
示例输入:4
示例输出:0 2 8 34
您可以使 fibonacci
函数成为只生成偶数斐波那契数的生成器,然后从中提取所需数量的值:
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))
打印:
0
2
8
34
改为使用 while 循环。
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()
输出:
0 2 8 34
你可以直接检查偶数:
def fibonacci(num=4):
fib1, fib2 = 1, 0
for _ in range(num):
print(fib2, end=' ')
fib1, fib2 = fib1 + 2*fib2, 2*fib1 + 3*fib2
考虑两个相邻的斐波那契数 a
和 b
(最初是 1 和 0),当您移动 window:
时会发生什么
a b # odd even
b a+b # even odd
a+b a+2b # odd odd
a+2b 2a+3b # odd 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()
我需要它输出指定个数的偶数
示例输入:4
示例输出:0 2 8 34
您可以使 fibonacci
函数成为只生成偶数斐波那契数的生成器,然后从中提取所需数量的值:
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))
打印:
0
2
8
34
改为使用 while 循环。
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()
输出: 0 2 8 34
你可以直接检查偶数:
def fibonacci(num=4):
fib1, fib2 = 1, 0
for _ in range(num):
print(fib2, end=' ')
fib1, fib2 = fib1 + 2*fib2, 2*fib1 + 3*fib2
考虑两个相邻的斐波那契数 a
和 b
(最初是 1 和 0),当您移动 window:
a b # odd even
b a+b # even odd
a+b a+2b # odd odd
a+2b 2a+3b # odd even
所以每三个斐波那契数都是偶数,最后一行还告诉你如何直接移动三步。