I'm trying to print all primes into a range of given numbers (low and max, given numbers included).
For example:
num1=10, num2=20
>>> 11, 13, 17, 19
My code fails in some occasions and I can't understand why:
num1 = int(input('First number is: '))
num2 = int(input('Second number is: '))
if num2 <= num1:
num1,num2 = num2,num1
for i in range(num1, num2+1):
for p in range(2,int(num2**0.5)+1):
if i%p == 0:
break
else:
print(i,' ',end = '')
print('\n')
Results:
1 to 7 >>> 1 3 5 7 (omits 2)
1 to 30 >>> 1 7 11 13 17 19 23 29 (omits 2,3,5)
1 to 60 >>> 1 7 11 13 17 19 23 29 (omits 2,3,5,7)
0 to 0 >>> 0 (prints 0 -> not a prime number)
0 to 7 >>> 1 3 5 7 (omits 2)
How can I correct this? Thanks a bunch!
ps. number 1 is not a prime too.
The mistake in your code was not having an i
in the second part of the inner for loop range as opposed to num2
num1 = int(input('First number is: '))
num2 = int(input('Second number is: '))
if num2 > num1:
num1, num2 = num2, num1
for i in range(num1, num2+1):
if i == 0 or i == 1: continue
for p in range(2,int(i**0.5)+1): # the second part should be int(i**0.5) + 1, not int(num2**0.5)+1
if i%p == 0:
break
else:
print(i,' ',end = '')
Also rather than having two branches for num1 < num2 and the other way around, you can do something like below. Further in terms of code design, it would be better to decompose this slightly into an is_prime
method. That way, if you ever want to write a quicker primality tester, you could easily edit the helper function as opposed to messing with the main code.
def is_prime(num):
if i == 1: return False
for p in range(2,int(num**0.5)+1):
if num % p == 0:
return False
return True
inp1 = int(input('First number is: '))
inp2 = int(input('Second number is: '))
num1 = min(inp1, inp2)
num2 = max(inp1, inp2)
for i in range(num1, num2+1):
if is_prime(i):
print(i,' ',end = '')
print('\n')