在进行OJ赛时,
题目:给你一个整数n,问最多能将其分解为多少质数的和。在第一行输出最多的质数数量k,下一行输出k个整数,为这些质数。
出现运行时错误
代码如下:
def main():
# code here
n = int(eval(input()))
list = []
for i in range(2, n + 1):
if i == 2:
list.append(i)
for j in range(2, i):
# i除以2到i-1之间的数,寻找素数2
if i % j == 0:
break
else:
list.append(i)
break
num = 0 # 统计数量
currentValue = 0 # 当前的值
currentList = [] #统计构成当前输入数字的质数
Sum(currentValue, list, n,currentList)
num=len(currentList)
print(num)
print(' '.join(str(i) for i in currentList))
pass
def Sum(currentValue, list, n,currentList):
for i in list:
if currentValue< n:
if currentValue+i<n:
currentValue+=i
currentList.append(i)
Sum(currentValue, list, n,currentList)
break
if currentValue+i==n:
currentList.append(i)
break
else:
currentValue-=i
currentList.remove(i)
if __name__ == '__main__':
main();
程序并没有错误,在pycharm上面能够运行出结果,在马蹄集上面测试也没有问题,一提交就出错。
结论:反复运行测试,发现问题,应该是出现递归上,当输入n值足够大时,会出现n/2+1左右次递归,内存直接爆了,即递归爆栈(一般由递归时层数过深导致的)。测试用例太小了,导致未发现问题,需要修改递归代码。如下图所示:
RecursionError: maximum recursion depth exceeded in comparison
RecursionError:在比较中超过了最大递归深度
去掉递归,修改Sum函数为如下:
def main():
# code here
n = int(eval(input()))
list = []
for i in range(2, n + 1):
if i == 2:
list.append(i)
for j in range(2, i):
# i除以2到i-1之间的数,寻找素数2
if i % j == 0:
break
else:
list.append(i)
break
num = 0 # 统计数量
currentValue = 0 # 当前的值
currentList = [] #统计构成当前输入数字的质数
Sum(currentValue, list, n,currentList)
num=len(currentList)
print(num)
print(' '.join(str(i) for i in currentList))
pass
def Sum(currentValue, list, n,currentList):
while currentValue< n:
for i in list:
while currentValue+i<n:
currentValue+=i
currentList.append(i)
if currentValue+i==n:
currentList.append(i)
break
elif currentValue+i>n:
currentValue-=i
currentList.remove(i)
break
if __name__ == '__main__':
main();
提交通过