How do I check if a number is divisible by every number in a list
Do you really mean every, surely to find a prime number you need to know if the number is divisible by any number in the list.
There are going to be neater, or faster, or more elegant solutions available, I've tried to put this one together from your own code and to make it as understandable as possible. However the function I've defined checks to see if a number is divisible by any number in the list as that is what is required for finding prime numbers. It also doesn't check any further numbers in the list once it has found one which the trial number can be divided by. HTH:
x = 9
# PrimeTarget is the nth prime number - the one being searched for.
PrimeTarget = 10001
PrimeList = [2, 3, 5, 7]
def check_prime(guess, primes):
# Routine to check if guess is divisible by any number in primes.
for prime_no in primes:
if guess % prime_no == 0:
# guess is divisible by a prime no.
# and thus not prime itself.
return False
# Only hit the next line if the guess was not divisible
# by any of the numbers in the list (primes)
return True
while len(PrimeList) < PrimeTarget:
if check_prime(x, PrimeList):
PrimeList.append(x)
x += 2
print (x)
print (PrimeList)
A potentailly neater function would be :
def check_prime(guess, primes):
return any( guess % x == 0 for x in primes)
If you really do want to check if a number is divisible by all numbers in a list, change that any
to an all