I want to create a python function that accepts two integer parameters finds all prime numbers between them and returns these primes in a list.
I did a part of the code but I'm stuck in printing prime numbers and turning them into a list.
a,n = map(int,input("Enter a and n: ").split())
def isPrime(a,n):
if n <= 1:
return False
for i in range(a, n 1):
if n % i == 0:
return False;
return True
CodePudding user response:
You can make your is_prime
function shorter like that:
a,n = map(int,input("Enter a and n: ").split(" "))
def is_prime(a):
return all(a % i for i in range(2, a))
out = []
for i in range(a, n):
if is_prime(i):
out.append(i)
print(out)
The output for a = 0 and n = 90 would be:
[0, 1, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89]
CodePudding user response:
I edited your solution so that you only check for numbers with a value of 2 or higher. Your solution allows negatives, which is not correct.
Also, your clause for checking for the primes is wrong, as you check if n
has divisors. Instead, you want to check if every number in [a, n) interval has a divisor. The interval is [a, n) because a prime number has only 1 and itself as divisors.
My code does just that, so if the algorithm finds that a number in the [a, n) interval has no divisors, then it will append it in an empty list that I created before going through the loop, and return the list, then print it.
a, n = map(int, input("Enter a and n: ").split())
def isPrime(a, n):
lst = []
for i in range(a, n 1):
if (i > 1):
for j in range(2, i):
if (i % j == 0):
break
else:
lst.append(i)
return lst
print(isPrime(a, n))
My output for a = 0 and n = 100 is:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
My code is a modified version of this.