Ido*_*dos 0 python algorithm largenumber numbers sum
我需要获得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
Run Code Online (Sandbox Code Playgroud)
你不需要两个循环.
首先,让我们将所有数字放在一个列表中:
>>> a = list(map(int, str(5**150000)))
Run Code Online (Sandbox Code Playgroud)
然后计算前50000位的总和:
>>> maximum = current = sum(a[:50000])
>>> current
225318
Run Code Online (Sandbox Code Playgroud)
现在,让我们循环遍历列表,从总和中删除最低位数,并在每次迭代期间添加下一个50000位数字:
>>> for i in range(0, len(a)-50000):
... current = current - a[i] + a[i+50000]
Run Code Online (Sandbox Code Playgroud)
检查新总和是否大于前一个,如果是,请将其设为新的"临时最大值":
... if current > maximum: maximum = current
...
Run Code Online (Sandbox Code Playgroud)
循环退出后,maximum包含最大值:
>>> maximum
225621
Run Code Online (Sandbox Code Playgroud)
让我们将它全部放入一个函数中,这样就不会出现复制错误:
def maxdigitsum(number, digits):
l = list(map(int, str(number)))
maximum = current = sum(l[:digits])
for i in range(0, len(l)-digits):
current = current - l[i] + l[i+digits]
if current > maximum: maximum = current
return maximum
Run Code Online (Sandbox Code Playgroud)