+ 8

This is my code for checking for prime numbers. Are there any problems? Can it be improved or optimized?

Prime numbers https://code.sololearn.com/c499Bfn1Ikfb/?ref=app

14th Dec 2018, 11:49 PM
Hobo
Hobo - avatar
5 odpowiedzi
+ 8
In addition to Jay's comment on your code: - you can lose the ==True on line 7 to speed it up as it doesn't need to be compared just tested. - you can speed up the loop by only checking the odds (2 would need to be a tested separately before hand.)
15th Dec 2018, 3:06 AM
John Wells
John Wells - avatar
+ 1
U can use a list and store prime numbers and check the division with these prime numbers till the prime number that is less than square root of your number instead of checking with odd numbers. Kind of dynamic algorithm https://code.sololearn.com/ckO3jvD9ecIS/?ref=app
16th Dec 2018, 1:35 PM
Alireza Senobari
Alireza Senobari - avatar
+ 1
Alireza Senobari your code isn't efficient for the comment left on it and doesn't do the same thing as the original (detecting whether the entered number is prime.) The only way it would be as efficient as Hobo's updated code is when you are processing a range or multiple numbers.
16th Dec 2018, 4:12 PM
John Wells
John Wells - avatar
0
What coding language is this?
18th Dec 2018, 6:44 AM
Daniel
0
Probably there are too many divisions, this may be replaced by a sum based method like the following, just it depends if you need to evaluate only one number or several numbers. Try a benchmark. https://code.sololearn.com/cZtrg6s7UoTJ/#
3rd Feb 2019, 2:24 PM
Manuel Soto
Manuel Soto - avatar