Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 自守程序的长运行时间_Python_Algorithm_Math_Time Complexity - Fatal编程技术网

Python 自守程序的长运行时间

Python 自守程序的长运行时间,python,algorithm,math,time-complexity,Python,Algorithm,Math,Time Complexity,我写了一个程序来求解第n个自守数(当数平方时,以原始数结尾的数)(例如6252=390625,390625%1000=625) 很抱歉代码不好,第一年的Comp Sci 我需要第5000次输入少于12秒的运行时间。当前代码大约需要45秒。 使用有意义的变量名;字母汤很难阅读 用整数进行计算,而不是从字符串转换。因为从1位数字开始,你就知道字符串长度;保持适当的10次方。不要串接和转换为整数,直接生成数字即可 代码 你能将这些东西应用到你现有的代码中吗?请注意,for的外部循环有一个不同的控件

我写了一个程序来求解第n个自守数(当数平方时,以原始数结尾的数)(例如6252=390625,390625%1000=625)

很抱歉代码不好,第一年的Comp Sci

我需要第5000次输入少于12秒的运行时间。当前代码大约需要45秒。

  • 使用有意义的变量名;字母汤很难阅读
  • 用整数进行计算,而不是从字符串转换。因为从1位数字开始,你就知道字符串长度;保持适当的10次方。不要串接和转换为整数,直接生成数字即可
代码

你能将这些东西应用到你现有的代码中吗?请注意,for的外部
循环有一个不同的控件;找到
n//2
次的5和6数字。你唯一关心较小的一次是在奇数
n
的最终迭代中


它在1.5秒内显示为绿色(5000)

只需几微秒即可工作 代码


Sweet n simple!

您可以使用pow函数计算模10的幂,以加快计算速度。例如
pow(n,2,10)
将返回n的最后一位数字squared@DanielGee感谢您的建议,不幸的是,运行时没有更改,但确实压缩了代码。这个问题更适合于这种情况,尤其是在这种情况下,使用
str
是时间密集型的。您可以使用逻辑运算重写它。但是如果您确实想要速度,请使用C programmin编写它g语言。它的速度可能会提高100倍或更多。这不是真正的问题,这些数字正以天文数字般的速度迅速变大(即NR24是9918212890625,你将无法使用蛮力,包括C)。你需要一个更好的算法,
import time
def green(n):
  start_time = time.time()
  f = 3
  if n==1:
    return 1
  elif n==2:
    return 5
  elif n==3:
    return 6
  n1 = "5"
  n2 = "6"
  tempn2 = "0"
  tempn1 = "0"
  x = 1
  while f!=n+1:
    if int(n1) > int(n2):
      tempn2 = str(x) + n2
      while int(pow(int(tempn2), 2, 10**(len(tempn2)))) != int(tempn2):
        tempn2 = str(x) + n2
        x+=1
      x=1
      f+=1
      n2 = tempn2
      if f==n+1:
        break
    else:
      tempn1 = str(x) + n1
      while int(pow(int(tempn1), 2, 10**len(tempn1))) != int(tempn1):
        tempn1 = str(x) + n1
        x+=1
      x=1
      f+=1
      n1 = tempn1
  print("--- %s seconds ---" % (time.time() - start_time))
  return min(int(n1), int(n2))
for f in range(1, n//2):
  ten_power = next_power    # Keep track of length in digits
  next_power *= 10

  # "old5" is the previous automorphic number ending in 5
  for digit in range(9, 0, -1):
      new5 = old5 + digit * ten_power
      new5sq = new5*new5
      if new5sq % next_power == new5:
          # you found the number
          old5 = new5
          break
n=int(input('Enter any no.'))
temp=n
div=1
while temp>=1:
    temp=temp//10
    div=div*10
x=n**2
y=x%div
if n==y:
    print(' Automorphic')
else:
    print(' Not Automorphic')