0
Quicker way to write code/execute function faster for higher numbers?
3 Réponses
+ 5
In your isPrime function, you only need to check divisibility up to the square root of n, not up to n itself. You should also only be checking odd numbers. (Increasing loop by 2).
I've never done python before but I believe it would look something like this:
for i in range(3, int(n**(0.5)), 2)
That will improve that functions computing speed by about 10x.
+ 8
In addition to limit testing to square root of tested number, you can store previous calculated primes number, and test divisibility only for primes ^^ ( it will drastically increase speed test for many testing number -- but not for only one ^^ )
0
That is exponentially faster. Thank you!