0

Quicker way to write code/execute function faster for higher numbers?

https://code.sololearn.com/cG4q5v7LqMBJ/?ref=app

1st Jun 2017, 3:20 AM
Derek
3 Answers
+ 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.
1st Jun 2017, 4:34 AM
Rrestoring faith
Rrestoring faith - avatar
+ 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 ^^ )
1st Jun 2017, 5:45 AM
visph
visph - avatar
0
That is exponentially faster. Thank you!
1st Jun 2017, 7:08 AM
Derek