225k views
2 votes
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

User Desertkun
by
5.3k points

1 Answer

4 votes

Answer:

Step-by-step explanation:

The following code is written in Javascript and is a function called primes that takes in a single parameter as an int variable named n. An array is created and looped through checking which one is prime. If So it, changes the value to true, otherwise it changes it to false. Then it creates another array that loops through the boolArray and grabs the actual numberical value of all the prime numbers. A test case for n=150 is created and the output can be seen in the image below highlighted in red.

function primes(n) {

//Boolean Array to check which numbers from 1 to n are prime

const boolArr = new Array(n + 1);

boolArr.fill(true);

boolArr[0] = boolArr[1] = false;

for (let i = 2; i <= Math.sqrt(n); i++) {

for (let j = 2; i * j <= n; j++) {

boolArr[i * j] = false;

}

}

//New Array for Only the Prime Numbers

const primeNums = new Array();

for (let x = 0; x <= boolArr.length; x++) {

if (boolArr[x] === true) {

primeNums.push(x);

}

}

return primeNums;

}

alert(primes(150));

Prime numbers can be generated by an algorithm known as the Sieve of Eratosthenes-example-1
User Yevgeny Simkin
by
4.9k points