How do I check if a number is divisible by every number in a list
你真的是说每,一定要找到一个素数,你需要知道这个数是否可以被列表中任何一个的数整除。在
将会有更简洁,更快,或者更优雅的解决方案,我试着把这一个从你自己的代码中组合起来,并使它尽可能容易理解。但是,我定义的函数检查一个数是否可以被列表中的任何一个数整除,因为这是寻找素数所需要的。它也不会检查列表中的任何进一步的数字,一旦它找到了一个可以除以试验号码。高温: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)
一个可能更简洁的功能是:
^{pr2}$
如果您确实想检查一个数字是否可以被列表中的所有数字整除,请将any改为all