答案 0 :(得分:1)
import sys
sys.setrecursionlimit (30000)
"""The checkprime function uses the prime factor theorum to determine if a number is prime by checking it against a list of
prime numbers and ensuring it is not divisible by said numbers, therefore ensuring it is a prime, it requires a list of all prime numbers
smaller than the number being checked itself"""
def checkprime(primelist,value,recursions):
#Decrease the index that is being looked at
recursions -= 1
#If the prime is not on
if recursions == -1:
return(True)
if value%primelist[recursions] == 0:
return(False)
return(checkprime(primelist,value,recursions))
'''The compileprimes function returns a list of all the prime numbers below the maximum value, using a list of primes,the function starts with a list of the first few prime numbers as a
default value and works up from there, its start value is naturally set to the following prime to avoid unneccesary checks'''
def compileprimes(Up_To,primelist=[2,3,5,7],start=11):
#Base case: If the value to compare is greater than the maximum value return the list of primes
if start > Up_To:
return(primelist)
#Use the checkprime function to check if the 'start' value is a prime
if checkprime(primelist,start,len(primelist)):
#If the 'start' value is prime, append it to the list of primes
primelist.append(start)
#Increase by two to skip all even numbers
start += 2
#Recursive step
return(compileprimes(Up_To,primelist,start))
compileprimes 函数将递归地创建一个质数列表,直到和低于您输入的数字。 例如。
'''
>>> compileprimes(23)
[2,3,5,7,11,13,17,23]
'''
您可能会遇到的一个问题是,再次调用该函数时,可能必须将 primelist
数组分配给默认值,但是该方法被认为比之前提出的解决方案高效得多,因为它没有除以任何非质数(它们本身是质数的乘积),它的工作速度也应该比前面的例子快得多。
删除 n 值下的任何数字很容易,所以我将把它留给你
答案 1 :(得分:-1)
def primes(m, n):
list_of_primes = [] # Keep track of primes
for num in range(m, n + 1): # make inclusive of upper bound
is_prime = True # Assume number is prime as starting condition
for i in range(2, num): # Check remainder from number 2 up to num
if num % i == 0:
is_prime = False
break
if is_prime and num > 1: #EDIT HERE
list_of_primes.append(num) #add to the list of primes if True
return list_of_primes
请注意,有多种方法可以改进此算法,例如不检查偶数等,但这符合您问题中定义的条件。