【发布时间】:2014-01-12 11:32:42
【问题描述】:
我正在尝试使用变量来查找所有斐波那契,并且如果可以被所选变量整除,则能够将它们相加。我也想尝试在不使用任何 fib() 或 memoization 的情况下编写它。
这是我的代码:
endNum = int(raw_input("Enter the end number here "))
divisable_by = int(raw_input("Sum all numbers in the sequence that divide by: "))
# below is the same as "a, b = 0, 1"
a = 0
b = 1
""" gave single letter variables to those above to use in formula below
(longer strings do not seem to work)"""
c = endNum
d = divisable_by
# while b is less than or equal to the ending number, it will loop.
while b <= c:
print b
# below is the same as "a, b = b, a+b"
a_old = a
a = b
b = a_old + b
# the below helps with summing the numbers that are divisable by number chosen.
total = 0
for i in range(a, c):
if i%d == 0:
total += i
#prints text and number calculated above.
print "Sum of all natural numbers that divide by the number you chose"
print "and are less than the other number you chose is: ", total
我能够运行代码,但我得到了错误的答案。例如,如果我运行代码将所有可被 3 整除的斐波那契数加到 21,我得到答案“0”。答案应该是“24 = (3 + 21)”。
任何关于简单修改的帮助都会很棒!
【问题讨论】:
标签: python while-loop fibonacci