题目:
有一个数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。
分析:
伪代码: t=2/1+3/2+5/3+8/5+13/8+21/13+34/21+55/34+89/55+144/89+233/144+377/233+610/377+987/610+1597/987+2584/1597+4181/2584+6765/4181+10946/6765+17711/10946
print(t) # 32.66026079864164
定义分母 n1 = 1 , 分子为 n2 = n1 +1 a = (n + n ) / n 第二个分数自增分母为 n1 = n2 分子为 n2 = n1 + n2 b = ((n+n)+n)/(n+n)
类似菲波纳茨算法 f(n-1) + f(n-2)
代码实现:
def sum3(num):
sum1 = 0
a = 1
b = a + 1
while True:
num -= 1
# c = b / a
# sum1 += c
sum1 += b / a
a, b = b, a + b
if num < 1:
break
return sum1
print(sum3(20))
代码运行结果:
32.66026079864164