我有这个python程序,用于计算给定数字的“平方免费数”。我遇到了有关时间复杂度的问题,这是我在在线编译器中收到“超出时间限制”错误。
number = int(input())
factors = []
perfectSquares = []
count = 0
total_len = 0
# Find All the Factors of the given number
for i in range(1, number):
if number%i == 0:
factors.append(i)
# Find total number of factors
total_len = len(factors)
for items in factors:
for i in range(1,total_len):
# Eleminate perfect square numbers
if items == i * i:
if items == 1:
factors.remove(items)
count += 1
else:
perfectSquares.append(items)
factors.remove(items)
count += 1
# Eleminate factors that are divisible by the perfect squares
for i in factors:
for j in perfectSquares:
if i%j == 0:
count +=1
# Print Total Square Free numbers
total_len -= count
print(total_len)
如何减少该程序的时间复杂度?那就是如何减少for循环,从而使程序以较小的时间复杂度执行?
首先,您只需要检查for i in range(1, number/2):
,因为number/2 + 1
和不能成为因素。
其次,您可以计算出可能是次线性时间因素的理想平方数:
squares = []
for i in range(1, math.floor(math.sqrt(number/2))):
squares.append(i**2)
第三,您可以搜索因子,当找到一个因子时,检查它是否不能被正方形整除,然后将其添加到因子列表中。
这种方法将为您节省for items in factors
嵌套循环块以及下一个块的所有时间。我不确定是否一定会更快,但是浪费更少。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句