Question: Write a function that generates a vector of prime numbers between 2 and n. The function has 1 parameter, n, and returns a vector of
Write a function that generates a vector of prime numbers between 2 and n. The function has 1 parameter, n, and returns a vector of integers. Use the Sieve of Eratosthenes to generate the vector of integers.
To find all the prime numbers less than or equal to a given integernby Eratosthenes' method:
Create a vector of consecutive integers from 2 throughn:(2, 3, 4, ...,n).Initially, letpequal 2, the smallest prime number.Enumerate the multiples ofpby counting tonfrom2pin increments ofp, and mark them in the list (these will be2p, 3p, 4p, ...; thepitself should not be marked).Find the first number greater thanpin the list that is not marked. If there was no such number, stop. Otherwise, letpnow equal this new number (which is the next prime), and repeat from step 3.When the algorithm terminates, the numbers remaining not marked in the list are all the primes belown.Copy the unmarked numbers to the vector that the function returns.
The main idea here is that every value given topwill be prime, because if it were composite it would be marked as a multiple of some other, smaller prime. Note that some of the numbers may be marked more than once (e.g., 15 will be marked both for 3 and 5).
As a refinement, it is sufficient to mark the numbers in step 3 starting fromp2, as all the smaller multiples ofpwill have already been marked at that point. This means that the algorithm is allowed to terminate in step 4 whenp2is greater thann.[1](Links to an external site.)Links to an external site.
Another refinement is to initially list odd numbers only,(3, 5, ...,n), and count in increments of2pfromp2in step 3, thus marking only odd multiples ofp. This actually appears in the original algorithm.[1](Links to an external site.)Links to an external site.This can be generalized withwheel factorization(Links to an external site.)Links to an external site., forming the initial list only from numberscoprime(Links to an external site.)Links to an external site.with the first few primes and not just from odds (i.e., numbers coprime with 2), and counting in the correspondingly adjusted increments so that only such multiples ofpare generated that are coprime with those small primes, in the first place
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
