Home > Back-end >  my python program is to find prime numbers between two intervals but i am getting 9 in the output ca
my python program is to find prime numbers between two intervals but i am getting 9 in the output ca

Time:06-09

python code to give prime numbers between two intervals

start = int(input('enter starting point of interval:'))
end = int(input('enter ending point of interval:'))
for i in range(start,end 1):
    if i>1:
        for j in range(2,i 1):
            if (i % j == 0):
                break
            else:
                print(i, end = " ")
                break

the output if i put start and end as 2,10 was 3,5,7,9 please tell what mistake i am doing

CodePudding user response:

In case of 9, you're checking if the number is divisible by 2, it's not, and then you print the number and don't check anything else.

You're also looping till i 1, meaning you check if the number is divisible by itself, which it is...

Try changing those:

start = int(input('enter starting point of interval:'))
end = int(input('enter ending point of interval:'))
for i in range(start,end 1):
    if i>1:
        for j in range(2,i):
            if (i % j == 0):
                break
        else:
            print(i, end = " ")

Also, instead of checking if i>1 in every loop, change the loop conditions, and you can loop until the square root.

End result:

import math
start = int(input('enter starting point of interval:'))
end = int(input('enter ending point of interval:'))
for i in range(max(start, 2),end 1):
    if i % 2 == 0  and i != 2: continue
    if all((i%j!=0) for j in range(3,int(math.sqrt(i)) 1, 2)):
        print(i, end = " ")
  • Related