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.
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.
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.
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)):
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With