而Python中的循环和斐波那契(不导入或使用“fib”)

时间:2013-12-24 08:08:30

标签: python while-loop fibonacci

我正在尝试使用变量来查找所有Fibonacci,并且如果可以选择变量,则可以将它们相加。我也想尝试不使用任何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整除的Fibonacci加起来,我得到的答案为“0”。答案应该是“24 =(3 + 21)”。

任何简单修改的​​帮助都会很棒!

3 个答案:

答案 0 :(得分:1)

您在每个循环中将总计重置为0。将其移出循环。也不要在每个循环中测试范围。这也会给你错误的结果。只测试找到的新号码。

答案 1 :(得分:0)

您需要先将斐波那契数字添加到列表中,以便稍后在进行除法检查时使用它们。其次,你需要从循环中取出总数,因为正如kgiannakakis所说,它总是被0代替。所以看起来应该是这样的:

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

fib_list = []
# while b is less than or equal to the ending number, it will loop.
while b <= c:
    print b
    fib_list.append(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 fib_list:
  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

此代码还会考虑您提供的最后一个数字,例如,如果它是21和3,则总数将为24(21和3可按3分割),如您所愿。然而,这不是你的印刷品所说的'并且比你选择的其他数字少'是......所以你应该考虑将它改为'更少或相等'

答案 2 :(得分:0)

生成器使用的内存少于列表综合。

def fibNum(n):
    a,b = 1,1
    while b < n:
        yield b
        b,a = a+b,b
n = int(raw_input("Enter the end number here "))
d = int(raw_input("Sum all numbers in the sequence that divide by: ")) 
total = sum(i for i in fibNum(n) if i%d == 0)
print ("Sum of all natural numbers that divide by the number you chose") 
print ("and are less than the other number you chose is: %d" %total)