Check for the prime numbers code and suggest any alternatives | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
29th Sep 2021, 2:47 PM
CHITTAMURU NIKHIL
4 Answers
+ 2
CHITTAMURU NIKHIL The code looks good, except it's quite inefficient... You shouldn't go through every single number when checking if the number is a prime you should at least go through sqrt(number) or even for i in range(3, int(sqrt(i)),2): (that's the method Coding Cat showed me ;) So, here is a better way to check if number is a prime: https://code.sololearn.com/cfO10uzSKk96/?ref=app Also check out this thread: https://www.sololearn.com/Discuss/2891515/?ref=app
29th Sep 2021, 3:10 PM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
0
Looks all good, quite efficient too
29th Sep 2021, 3:00 PM
Kamil Hamid
Kamil Hamid - avatar
0
A thing to note is that if the number input could be very big, it is worth putting a break in the if clause on line 11, so that it doesn’t take extremely long in the loop, when it is established the number is not prime
29th Sep 2021, 3:04 PM
Kamil Hamid
Kamil Hamid - avatar
0
This is a little faster and more compact. https://code.sololearn.com/crkg94t1xKJt/?ref=app This implements the Primes Sieve of Eratosthenes, which uses more memory but is amazingly fast. https://code.sololearn.com/clyThoszsdj9/?ref=app
29th Sep 2021, 5:49 PM
Brian
Brian - avatar