Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

There is a 4 in my prime number list generated in Python

Tags:

python

Here is my code.

#Prime numbers between 0-100
for i in range(2,100):
    flg=0
    for j in range(2,int(i/2)):
        if i%j==0:
            flg=1
            break
    if flg!=1:
        print(i)

And the output is

2
3
4 <-
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

I have no idea why there is this 4. Pardon me if i made some noobish mistake, as i can't seem to figure it out.

like image 267
Gokul1794 Avatar asked Dec 16 '13 11:12

Gokul1794


People also ask

How do you check if a number is prime in a list Python?

We check if num is exactly divisible by any number from 2 to num - 1 . If we find a factor in that range, the number is not prime, so we set flag to True and break out of the loop. Outside the loop, we check if flag is True or False . If it is True , num is not a prime number.

How do you find the prime number in a while loop in Python?

Show activity on this post. flag = 0 n = int(input('\nEnter whole number to check : ')) i = 2 while i <= (n/2): if (n%i) == 0: flag = 1 break if n == 1: print('1 is neither prime nor composite') elif flag == 0: print(n,' is a prime number.


1 Answers

The reason is that range is not inclusive, i.e.

>>> range(2,2)
[]

So when you access 4, you don't check for divisors. Change for example to range(2,int(i/2)+1)

To speed up your calculation, you can use math.sqrt instead of /2 operation, for example as:

import math

and then

for j in range(2, int(math.sqrt(i)+1)):
like image 67
alko Avatar answered Nov 14 '22 23:11

alko