I am trying to learn Python programming, and I'm pretty new at this.
I was having issues in printing a series of prime numbers from one to hundred. I can't figure our what's wrong with my code.
Here's what I wrote; it prints all the odd numbers instead of primes:
for num in range(1,101):
for i in range(2,num):
if (num%i==0):
break
else:
print(num)
break
A simpler and more efficient way of solving this is storing all prime numbers found previously and checking if the next number is a multiple of any of the smaller primes.
Note that
any
is a short circuit function, in other words, it will break the loop as soon as a truthy value is found.This is a sample program I wrote to check if a number is prime or not.
I'm a proponent of not assuming the best solution and testing it. Below are some modifications I did to create simple classes of examples by both @igor-chubin and @user448810. First off let me say it's all great information, thank you guys. But I have to acknowledge @user448810 for his clever solution, which turns out to be the fastest by far (of those I tested). So kudos to you, sir! In all examples I use a values of 1 million (1,000,000) as n.
Please feel free to try the code out.
Good luck!
Method 1 as described by Igor Chubin:
Benchmark: Over 272+ seconds
Method 2 as described by Igor Chubin:
Benchmark: 73.3420000076 seconds
Method 3 as described by Igor Chubin:
Benchmark: 11.3580000401 seconds
Method 4 as described by Igor Chubin:
Benchmark: 8.7009999752 seconds
Method 5 as described by user448810 (which I thought was quite clever):
Benchmark: 1.12000012398 seconds
Notes: Solution 5 listed above (as proposed by user448810) turned out to be the fastest and honestly quiet creative and clever. I love it. Thanks guys!!
EDIT: Oh, and by the way, I didn't feel there was any need to import the math library for the square root of a value as the equivalent is just (n**.5). Otherwise I didn't edit much other then make the values get stored in and output array to be returned by the class. Also, it would probably be a bit more efficient to store the results to a file than verbose and could save a lot on memory if it was just one at a time but would cost a little bit more time due to disk writes. I think there is always room for improvement though. So hopefully the code makes sense guys.
Here is the simplest logic for beginners to get prime numbers:
How about this? Reading all the suggestions I used this:
Prime numbers up to 1000000