0

我需要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
4

2 回答 2

6

你不需要两个循环。

首先,让我们将所有数字放在一个列表中:

>>> a = list(map(int, str(5**150000)))

然后计算前 50000 位数字的总和:

>>> maximum = current = sum(a[:50000])
>>> current
225318

现在,让我们遍历列表,从总和中删除最低位,并在每次迭代期间将下一个 50000 位添加到前面:

>>> for i in range(0, len(a)-50000):
...     current = current - a[i] + a[i+50000]

检查新的总和是否大于前一个,如果是,则将其设为新的“临时最大值”:

...     if current > maximum: maximum = current
...

一旦循环退出,maximum包含最大值:

>>> maximum
225621

让我们把它全部放到一个函数中,这样就不会出现复制错误:

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
于 2013-03-24T16:33:52.133 回答
1
#!/usr/bin/python
def maxSumOfNConsecutiveDigits(number,numberConsecutiveDigits):
    digits = [int(i) for i in str(number)]
    consecutiveSum = sum(digits[:numberConsecutiveDigits])
    largestSum = consecutiveSum
    for i in xrange(numberConsecutiveDigits,len(digits)):
        consecutiveSum += (digits[i]- digits[i - numberConsecutiveDigits])
        largestSum = max(largestSum, consecutiveSum)
    return largestSum
print maxSumOfNConsecutiveDigits(5**150000,50000)
于 2013-03-24T16:33:47.400 回答