Python中大数N个连续数字的和
我需要找出一个大数字中,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
2 个回答
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)
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