+ 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
5 Answers
+ 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.)
+ 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
+ 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.
0
What coding language is this?
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/#