Question: ** JavaScript** This program will be run at the command prompt, not in a web browser. Prime numbers can be generated by an algorithm known

** JavaScript** This program will be run at the command prompt, not in a web browser.

Prime numbers can be generated by an algorithm known as the Sieve of Eratosthenes. The algorithm for this procedure is presented here. Write a program called primes.js that implements this algorithm. Have the program find and display all the prime numbers up to n = 150. Sieve of Eratosthenes Algorithm To Display All Prime Numbers Between 1 and n

Step 1: We need to start with all the numbers representing the range of numbers that are possible candidate primes. So, create an array of consecutive integers from 2 to n: (2,3,4,..n). I wouldnt hand-code this. I would use a loop to populate the array.

Step 2: At each step we select the smallest number and remove all its multiples. So well start with an outer loop that goes from 2 to n. initially, let p equal 2, the first prime number.

Step 3: In an inner loop we need to iterate over all the numbers that are multiples of p, i.e for 2, thats 2,4,6,8 etc. Each time, setting its value to false in the original array.

Step 4: Find the first number greater than p in the list that is not marked False. If there was no such number, stop. Otherwise, let p now equal this number( which is the next prime), and repeat from step 3. When the algorithm terminates, all the numbers in the list that are not marked False are prime.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!