Answered step by step
Verified Expert Solution
Question
1 Approved Answer
A prime number is any integer greater than one that is evenly divisible only by itself and 1. The Sieve of Eratosthenes is an ancient
A prime number is any integer greater than one that is evenly divisible only by itself and 1. The Sieve of Eratosthenes is an ancient method of finding prime numbers. We could apply it using rocks, but we have computers, so we will use them. The sieve operates as follows: 1. Create a std::vector of type bool with all elements initialized to true. Vector indices in C++ begin at 0 . The sieve is constructed to ignore element 0 and 1 (those indices are not prime numbers) and to generate a vector where any index that is a prime number will contain a value of true in that array position. All other array elements will eventually be set to false. 2. Starting with array index 2, look through the remainder of the array and set to false every element whose index is a multiple of two (except 2). Continue the process with the next element with value true (which will be 3) set to false array positions at multiples of 3 . For array index 2 , all elements beyond element 2 in the array that have indices which are multiples of 2(4,6,8,10, etc. ) will be set to false; for array index 3 , all elements beyond element 3 in the array that have indices which are multiples of 3 (indices 6,9,12,15, etc.) will be set to false; and so on. When this process completes, the array elements that are still true indicate that the index is a prime number. If Eratosthenes used rocks to illustrate how this works, he might have made 100 piles of rocks, each pile containing a number of rocks matching its place in the sieve, and then knocking non-prime piles out of the running. But since we can write C++ programs, we will use an array of one million elements to compute the "sieve" of prime numbers, and then create a table representing what we will call The Prime Number Histogram, with 10 entries: The Prime Number Histogram (\# of Primes in each interval) 2-99999:XXX100000-199999:200000-299999:300000-399999:400000-499999:(etc.)XXXXXXXXXXXX You can speed up the code significantly by limiting the outer loop to the square root of the size of the vector and by starting the inner loop at the square of the index of the outer loop, as demonstrated by this pseudocode
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started