-1

我刚刚完成 Project Euler,没有问题。1 for Python ...链接如下:

http://projecteuler.net/problem=1

我在python中提出了以下解决方案...

#!/usr/bin/env python

def main():
    print("The answer will be calculated shortly...")

if __name__ == "__main__":
    main()

n = 1000
n=-1

def isMultiple(i):
    if (i % 3 == 0) or (i % 5 == 0):
        if (i % 3 == 0) and (i % 5 == 0):
            return False
        else:
            return True


sum = 0
for i in range(3, n):
    if isMultiple(i):
        sum+=1
    print("The answer is... ", sum)

但是,运行此解决方案时给出的所有内容是:

[arch@archlinux Project Euler]$ python 1000-multi3or5.py
The answer will be calculated shortly...
[arch@archlinux Project Euler]$ 

我真的不明白出了什么问题,你能帮我解释一下为什么吗?非常感谢您花时间阅读本文,特别是如果您愿意帮助我。:)

4

1 回答 1

2

因为循环永远不会发生:

n = 1000
n=-1

然后在最后:

for i in range(3, n):

您正在运行从 3 到 -1 的范围。

In [4]: range(3, -1)
Out[4]: []

将行更改为:

n -= 1

它应该工作:

In [9]: n = 20 # Just to show a smaller output - your n would be 999 obviously
   ...: sum = 0
   ...: for i in range(3, n):
   ...:     if isMultiple(i):
   ...:         sum+=1
   ...:     print("The answer is... ", sum)
   ...:     
('The answer is... ', 1)
('The answer is... ', 1)
('The answer is... ', 2)
('The answer is... ', 3)
('The answer is... ', 3)
('The answer is... ', 3)
('The answer is... ', 4)
('The answer is... ', 5)
('The answer is... ', 5)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 6)
('The answer is... ', 7)
('The answer is... ', 7)
于 2013-04-19T11:30:40.900 回答