【发布时间】:2016-01-12 13:32:39
【问题描述】:
我有一个函数可以告诉我一个数字的因数,然后应该打印它有多少。
factors = 0
def getFactors(n):
global factors
for i in range(1,n):
if n%i==0:
print(i)
factors += 1
print(n, "has", factors, "factors.")
但是,因子的数量似乎是错误的。显然 16 有 6 个因子,尽管它明确列出了 4 个。
>>> getFactors(16)
1
2
4
8
16 has 6 factors.
>>>
我在这里做错了什么?
【问题讨论】:
-
你不需要一直到
n。显然,一个因子不能大于n/2。因此,您可以使用range(1, n/2)节省一半的迭代
标签: python python-3.x if-statement for-loop