Python finding Prime Numbers between any two numbers -
i'm trying find prime numbers between 2 random numbers.
firstly, have written code like:
m,n = map(int, raw_input().split()) in range(m, n+1): j in range(2, i): if i%j == 0: break else: print i,
now test case suppose enter 2, 30 prints
2 3 5 7 11 13 17 19 23 29
now analyzing, don't need loop till "i" in second loop rather can same looping till i/2, changed code as:
m,n = map(int, raw_input().split()) in range(m, n+1): j in range(2, int(i/2)+1): if i%j == 0: break else: print i,
then result same above while looped till i/2 in second loop.
now, i'm trying use sieve of eratosthenes method print prime numbers , used code as:
m,n = map(int, raw_input().split()) in range(m, n+1): sqrt_num = int(n**(0.5)) j in range(2, sqrt_num+1): if i%j == 0: break else: print i,
but prints
7 11 13 17 19 23 29
for same input.
please me understand doing wrong. , how can accomplish same using method.
your inner loop used loop until i-1
or i/2
. inner loop short when i
small, , longer when i
got larger.
now, inner loop goes sqrt_num
, constant computed n
. difference in behavior.
consider i = 3
, inner loop runs j = 2
j = 5
, , find case i%j == 0
... specifically, when j == 3
.
to clear: problem "sqrt_num
, constant". change square root of outer index, i
.
sqrt_num = int(i**(0.5))
Comments
Post a Comment