我有任务要做。问题是这样的。你给一个数字,比如x。程序计算从1开始的数字的平方,只有当它是回文时才打印出来。程序将继续打印这些数字,直到达到您提供的数字x。在
我已经解决了这个问题。对于正常运行时间x=10000000,它可以正常工作。在一个合理的时间内执行,工作正常。我想提高代码的效率。如果需要,我愿意修改整个代码。我的目标是制作一个能在5分钟内执行10^20的程序。在limit = int(input("Enter a number"))
def palindrome(limit):
count = 1
base = 1
while count < limit:
base = base * base #square the number
base = list(str(base)) #convert the number into a list of strings
rbase = base[:] #make a copy of the number
rbase.reverse() #reverse this copy
if len(base) > 1:
i = 0
flag = 1
while i < len(base) and flag == 1:
if base[i] == rbase[i]: #compare the values at the indices
flag = 1
else:
flag = 0
i += 1
if flag == 1:
print(''.join(base)) #print if values match
base = ''.join(base)
base = int(base)
base = count + 1
count = count + 1
palindrome(limit)