- 遍历求解(耗时过长,占用过多内存)
while True:
try:
m = int(input())
m3 = pow(m,3)
odd_set = [i for i in range(1,m3,2)]
odd_num = len(odd_set)
for i in range(odd_num-m):
odd_sub=odd_set[i:i+m]
num = sum(odd_sub)
if num == m3:
print("+".join(list(map(str,odd_sub))))
except:
break
- 利用数学公式求解
while True:
try:
m = int(input())
m3 = pow(m,3)
a = int((m3 - m*(m-1))/m)
string=""
for i in range(m):
string+=str(a)
string+='+'
a+=2
print(string[:-1])
except:
break
去掉最后一个字符可以用 str[:-1]