Answered step by step
Verified Expert Solution
Question
1 Approved Answer
I need help with a javascript assignment: 4. Prime numbers can be generated by an algorithm known as the Sieve of Eratosthenes. The algorithm for
I need help with a javascript assignment:
4. Prime numbers can be generated by an algorithm known as the Sieve of Eratosthenes. The algorithm for this procedure is presented here. Writea program called primes.js that implements this algorithm. Have the program find aslaay l rinc: up ton150 Sieve of Eratosthenes Algorithm To Display All Prime Numbers Between 1 and n Step 1 numbers that are possible candidate primes. So, create an array of consecutive integers from 2 to n: (2,3,4,. n). I wouldn't hand-code this. I would use a loop to populate the array. We need to start with all the numbers representing the range of Step 2: At each step we select the smallest number and remove all it's multiples. So we'll 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, that's 2,4,6,8 etc. Each time, setting it's 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 When the algorithm terminates, all the numbers in the list that are not marked False are prime. Example: Let us take an example when n 50. So we need to print all print numbers smaller than or equal to 50 We create a ist of umbers from 2 to 50 17 43 4445 46 47 48 49 50 According to the algorithm we will mark all the numbers which are divisible by 2 13 15 17 12 22 32 20 21 24 25 26 27 28 2930 43 44 45 46 Now we move to our next unmarked number 3 and mark all the numbers which are multiples of 28 29 30 34 35 38 47 50 We move to our next unmarked number 5 and mark all multiples of 5 13 14 15 16 17 18 19 20 25 28 1 42 43 44 45 4647 48 49 50 We continue this process and our final table will look like below: 14 1516 21 22 23 24 31 32 41 42 17 18 19 20 25 26 27 28 29 30 37 38 39 40 50 So the prime numbers are the unmarked ones: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47
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