我相信這個問題已經被問了很多,但我已經檢查過其他論壇,並試圖解決這個問題,這似乎沒有幫助。我認爲有一個溢出問題,但我不記得如何解決它。我花了很長時間從編碼中解脫出來(我的錯在那裏),所以我正在嘗試一些問題來幫助我擺脫困境。所以,只是想知道哪裏出了問題。當我嘗試n = 1000
的答案是錯誤的,但數字小於這似乎是正確的。由於大數字不會工作,我認爲這是一個整數溢出。整數溢出3和5的倍數
def n_number():
n = raw_input("Enter a max number: ")
try:
int(n)
return n
except ValueError:
print 'Value is not an integer'
exit(1)
# 'function that will add multiples of 3 and 5 that are less than the given value, n.'
def sum_multiplies(n):
sum = long(0)
counter3, counter5 = int(1),int(1)
value3 = 3*counter3
value5 = 5*counter5
while True:
# 'sums of multiples of 5\'s less than n'
if value5<int(n):
sum+= value5
counter5+=1
value5 = 5*counter5
# 'sums of multiples of 3\'s less than n'
if value3<int(n):
sum+= value3
counter3+=1
value3 = 3*counter3
else:
break
print "sum: %s" %sum
print "counter3: %s" %counter3
print "counter5: %s" %counter5
def main():
'max number is in n'
n = n_number()
sum_multiplies(n)
if __name__ == "__main__":
main()
你不能在Python溢出'int's,它們是任意精度的(模仿Python 2中的'long'實現細節,以及像range這樣的瘋狂內建函數實際上會拋出'OverflowError',因爲它們只能執行C'double')。 – Julian 2012-07-27 20:52:45
溢出沒有問題,使用mod('%')運算符來確定給定的數字是否可被其他整數所整除。例如。 'n%3 == 0'表示'n'能被3等整除 – Levon 2012-07-27 20:53:02
這可以簡單得多:'sum((x for x in range(1000)if x%3 == 0 or x%5 == 0))' – mgilson 2012-07-27 20:53:42