+ 4

Which code is the better one?

Which one of these two codes for testing if an Integer is a prime is better in your opinion? And why? https://code.sololearn.com/c2VfEBa7MRJm/?ref=app https://code.sololearn.com/ciXK21fW2XmP/?ref=app

5th Aug 2017, 1:51 PM
Jonas Schröter
Jonas Schröter - avatar
3 Answers
+ 5
The second one doesn't give more efficiency ^^ You can improve the first version by 2 ways, one will improve by less computation, second (kind of yours in 2.0) will be widely more efficient for many numbers tested for prime (not much improvement if only one number tested)... + rather than limit your test division to n/2, you can limit it to sqr(n), because when you have tested them you have tested all possibility: n == sqr(n)*sqr(n) so for x > sqr(n): n == x*y y < sqr(n) so y already tested because y < x + the second way to improve, will make sparing very much time (all the more if numberous tested number) by storing primes found and only test division for primes <= sqr(n)... It will consume a little more time for the first tested number (if you doesn't provide a hard coded base primes list), but you will spare a bunch of division computation, and next you only lost time for unregistered primes to test ;) Check this JS tuto-code for prime number test which implement these ways: https://code.sololearn.com/WPXD8LSoeiIL/?ref=app ... and this Python implementation (not commented): https://code.sololearn.com/cOdE3LoiYYkQ/?ref=app
6th Aug 2017, 7:19 AM
visph
visph - avatar
+ 4
Thank you, if I find some time to code, I'm going to improve my code.
6th Aug 2017, 7:41 AM
Jonas Schröter
Jonas Schröter - avatar
+ 2
You can solve a problem in countless ways. But IMHO, the best solution is the simplest one. Because, that's easier for others to understand and also because executing less code most of the time results a faster running program. So, i'll say, the 1st link is better.
5th Aug 2017, 3:18 PM
Salekin
Salekin - avatar