gpt4 book ai didi

python - 斐波那契加法器 - 计算斐波那契数列中的数字

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:46 25 4
gpt4 key购买 nike

我正在开发一个程序,该程序将计算具有某些数字限制的斐波那契数(即第一个具有 100 位数字的斐波那契数)。我下面的代码总体正在运行,但我遇到了一个让我难倒的逻辑错误。

代码的目标是以类似于二进制加法的方式计算斐波那契数。使用数组时,每个元素都保存 0 - 9 之间的数字,因此每个数组索引代表 10 的位置。

它开始正常工作并循环,但由于循环的处理方式,它在 13 到 21 之间停止。它将 10 位的数字相加,然后保存一个 31 数字。

有没有办法打破或阻止它把我没有看到的那些加在一起?

num1 = [0]*100
num2 = [0]*100
num2[len(num2)-1] = 1
carry = 0
flag = True

while (flag):
#Main for loop to work through the array
for count in range (1, len(num2)):
carry = num2[len(num2) - count] + num1[len(num1) - count]
if carry > 9:
num2[len(num2)- (count + 1)] = num2[len(num2)- (count + 1)] + 1
carry = carry % 10
num1[len(num1) - count] = num2[len(num2) - count]
num2[len(num2) - count] = carry
else:
num1[len(num1) - count] = num2[len(num2) - count]
num2[len(num2) - count] = carry
print(num2)
if num2[0] != 0:
flag = False

每次它通过主 while 循环时我都希望看到

[0,0,...,0,1]
[0,0,...,0,2]
[0,0,...,0,3]
[0,0,...,0,5]
[0,0,...,0,8]
[0,0,...,1,3]
[0,0,...,2,1]
...

但在到达 [...,2,1] 循环后,它会移动到 [...,3,1]

最佳答案

这是我相信您想要了解的内容的一个更清晰的版本。

#Init of Fib variables 
a = 0
b = 1
num = 10 #Change this to the number of fib calculation loops.
x = 0
output_arr_len = 100 #Change this to 10 for testing, as it's easier to see.

while x < num:
#Calculate Fib Sequence
c = a + b
a = b
b = c
x += 1

#Output Array
print([0] * (output_arr_len - len(str(c))) + [int(i) for i in str(c)])

下面是前 20 个循环的输出,其中 output_arr_len 设置为 10。

[0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 2]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 3]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 5]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 8]
[0, 0, 0, 0, 0, 0, 0, 0, 1, 3]
[0, 0, 0, 0, 0, 0, 0, 0, 2, 1]
[0, 0, 0, 0, 0, 0, 0, 0, 3, 4]
[0, 0, 0, 0, 0, 0, 0, 0, 5, 5]
[0, 0, 0, 0, 0, 0, 0, 0, 8, 9]
[0, 0, 0, 0, 0, 0, 0, 1, 4, 4]
[0, 0, 0, 0, 0, 0, 0, 2, 3, 3]
[0, 0, 0, 0, 0, 0, 0, 3, 7, 7]
[0, 0, 0, 0, 0, 0, 0, 6, 1, 0]
[0, 0, 0, 0, 0, 0, 0, 9, 8, 7]
[0, 0, 0, 0, 0, 0, 1, 5, 9, 7]
[0, 0, 0, 0, 0, 0, 2, 5, 8, 4]
[0, 0, 0, 0, 0, 0, 4, 1, 8, 1]
[0, 0, 0, 0, 0, 0, 6, 7, 6, 5]
[0, 0, 0, 0, 0, 1, 0, 9, 4, 6]

关于python - 斐波那契加法器 - 计算斐波那契数列中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57982123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com