[英]Why does the program take so long to run?
since your program has 2 for loops that fully iterate, your program time complexity is O(n**2) so it is expected to take so long time, you can do some optimizations in your code:由于您的程序有 2 个完全迭代的 for 循环,您的程序时间复杂度为 O(n**2),因此预计需要很长时间,您可以在代码中进行一些优化:
import math
def is_prime(number):
for i in range(2, int(math.sqrt(number) + 1)):
if (number % i) == 0:
return False
return True
Think about it logically, the larger the range, larger the number of iterations/loops for j.从逻辑上想想,范围越大,j 的迭代/循环次数就越大。 And then again the larger each individual number of j gets which is fed in to is_prime, the larger the i loop gets as well.
然后再次输入 is_prime 的 j 的每个单独数量越大,i 循环也越大。 Thus compounding the length of time it takes to run.
从而增加了运行所需的时间长度。
Your i loop needs to be smarter.您的 i 循环需要更智能。 Is there a need to check any more i numbers are factors of j once count its larger than 2?
一旦计数大于 2,是否需要检查更多 i 个数字是 j 的因子? ;)
;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.