简体   繁体   English

为什么程序运行需要这么长时间?

[英]Why does the program take so long to run?

I'm trying to solve a question from Project Euler using Python.我正在尝试使用 Python 解决 Project Euler 中的一个问题。 Why does my code take so long to run when the range of j is huge.当 j 的范围很大时,为什么我的代码需要这么长时间才能运行。 It works just fine when j has a small range.当 j 的范围很小时,它工作得很好。

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM