user1546721 - 9 months ago 51

Python Question

I am trying to learn Python programming, 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. Hope someone could help me out with this. 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

Answer

You need to check all numbers from 2 to n-1 (to sqrt(n) actually, but ok, let it be n).
If `n`

is divisible by any of the numbers, it is not prime. If a number is prime, print it.

```
for num in range(1,101):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print num
```

You can write the same much shorter and more pythonic:

```
for num in range(1,101):
if all(num%i!=0 for i in range(2,num)):
print num
```

As I've said already, it would be better to check divisors not from 2 to n-1, but from 2 to sqrt(n):

```
import math
for num in range(1,101):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print num
```

For small numbers like 101 it doesn't matter, but for 10**8 the difference will be really big.

You can improve it a little more by incrementing the range you check by 2, and thereby only checking odd numbers. Like so:

```
import math
print 2
for num in range(3,101,2):
if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)):
print num
```