【发布时间】:2013-03-24 16:23:51
【问题描述】:
我需要在一个很大的数字范围内得到n连续数字的最大总和。
例如,范围可以是5^150000,在这个范围内我想找出50,000个连续数字的最大和。
我使用两个循环的方法似乎永远不会终止。如有任何意见,我将不胜感激。
代码:
count = 0
tempsum = 0
summ = 0 # variables init
oldlist = ''
newlist = ''
num = str(3**2209) # for example
for digit in num: # go over all the digits in the number
while count < 12 and len(num) >= 12 : # check in 12-digits blocks while possible
oldlist += num[count] # update old list with new digit
tempsum += int(num[count]) # add current digit to sum
count += 1
if tempsum > summ: # check if new sum is larger than old one
summ = tempsum # update sum
newlist = oldlist # update the sequence list
oldlist = ''
count = 0
tempsum = 0
num = num[1:] # slice the 'first' digit of the number
print(newlist, summ) # print sequence and desired sum
【问题讨论】:
-
请向我们展示您的代码。
-
重复:stackoverflow.com/questions/15300995/… 至少,它是基于同一个数学问题。我不明白为什么它被关闭为
too localized。另一个关闭为not a real question。我认为这两种技术都足够通用,对后来的 SO-ers 有用。
标签: python algorithm numbers sum largenumber