write a recursive function that finds prime numbers using the following method:
ID: 3629254 • Letter: W
Question
write a recursive function that finds prime numbers using thefollowing method: start with a given list of the numbers from 2 to some limit, written in
order. Select the first element, which will be a prime number. Then remove all the values
that are a multiple of the first element. Repeat until the list is empty. This function takes a
list as input and prints all prime numbers within the list.
Explanation / Answer
def findPrimes(myList): # If the list is empty, then we're done if (myList == []): return # We're going to divide each element by the first element and check remainder factor = myList[0] # The first element is prime, so print it print factor; # Remove the first element form the list myList.pop(0) # Loop over list, and if the number divides evenly by the factor then remove it for i in range(1, len(myList)): if (i >= len(myList)): break if (myList[i] % factor == 0): myList.pop(i) # Call recursively with our reduced list findPrimes(myList) # Call the function with a sample list with numbers from 2 to 100 l = range(2,100) findPrimes(l)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.