Prime checking program not working on certain numbers - javascript

I was excited because my prime number program was working, but when I tried certain numbers like 5 and 10, 2 and 11, it wasn't working. I have tried to figure it out myself, and by looking at other things related to what I was doing, but I couldn't figure it out. I would appreciate an answer and thank everyone who helps, because I am just a beginner at coding and want to learn more.
var minimum;
var maximum;
var primes;
function myFunction(e) {
e.preventDefault();
minimum = document.getElementById('Minimum').value;
maximum = document.getElementById('Maximum').value;
primes = [];
listOfPrimes(minimum, maximum);
primes = primes.filter(function(x) {
return x > 1;
});
primes = primes.toString();
primes = primes.replace(/,(?=[^\s])/g, ", ");
document.getElementById("Your_Primes").innerHTML = primes;
}
function isPrime(num) {
for (var i = 2; i <= num / 2; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
function listOfPrimes(min, max) {
for (var j = min; j <= max; j++) {
isPrime(j);
}
}
body {
background-color: #dbdbdb;
}
#prime-checker {
background-color: #89a9dd;
margin: 5px;
padding: 5px;
text-align: center;
}
.the-primes {
background-color: #587cb7;
padding: 15px;
margin: 10px;
}
<!doctype html>
<html>
<head>
<title>Prime Lister</title>
<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="prime-checker">
<form>
<h2>Minimum Number:</h2><br>
<input type="number" placeholder="MinimumWholeNumber" id="Minimum" multiple="1" min="0" required><br><br>
<h2>Maximum Number:</h2><br>
<input type="number" placeholder="MaximumWholeNumber" id="Maximum" multiple="1" min="0" required><br><br><br>
<button id="button" onclick="myFunction(event)">Enter</button>
</form>
<div class="the-primes"><h2>Your Primes:</h2>
<p id="Your_Primes"></p>
</div>
</div>
<script type="text/javascript" src="Web_Prime_Lister.js"></script>
</body>
</html>

Your code for calculating a prime looks fine. The problem is that you are using the raw strings from the minimum and maximum to create your range. The problem is that strings are compared lexigraphically, so:
"2" < "100" // false
So when you pass those values into your function listOfPrimes, that loop will terminate early due to the string comparison.
To fix it, just convert your input values to numbers before you use them:
minimum = Number(document.getElementById('Minimum').value);
maximum = Number(document.getElementById('Maximum').value);
Here's your snippet with that fix, everything looks like it's working well:
var minimum;
var maximum;
var primes;
function myFunction(e) {
e.preventDefault();
minimum = Number(document.getElementById('Minimum').value);
maximum = Number(document.getElementById('Maximum').value);
primes = [];
listOfPrimes(minimum, maximum);
primes = primes.filter(function(x) {
return x > 1;
});
primes = primes.toString();
primes = primes.replace(/,(?=[^\s])/g, ", ");
document.getElementById("Your_Primes").innerHTML = primes;
}
function isPrime(num) {
for (var i = 2; i <= num / 2; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
function listOfPrimes(min, max) {
for (var j = min; j <= max; j++) {
isPrime(j);
}
}
body {
background-color: #dbdbdb;
}
#prime-checker {
background-color: #89a9dd;
margin: 5px;
padding: 5px;
text-align: center;
}
.the-primes {
background-color: #587cb7;
padding: 15px;
margin: 10px;
}
<!doctype html>
<html>
<head>
<title>Prime Lister</title>
<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="prime-checker">
<form>
<h2>Minimum Number:</h2><br>
<input type="number" placeholder="MinimumWholeNumber" id="Minimum" multiple="1" min="0" required><br><br>
<h2>Maximum Number:</h2><br>
<input type="number" placeholder="MaximumWholeNumber" id="Maximum" multiple="1" min="0" required><br><br><br>
<button id="button" onclick="myFunction(event)">Enter</button>
</form>
<div class="the-primes"><h2>Your Primes:</h2>
<p id="Your_Primes"></p>
</div>
</div>
<script type="text/javascript" src="Web_Prime_Lister.js"></script>
</body>
</html>
PS: You can further optimize your isPrime function by only checking divisors up to Math.floor(Math.sqrt(num)). That will save you many many iterations, especially for a large number. So:
function isPrime(num) {
var max = Math.floor(Math.sqrt(num));
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
primes.push(num);
}
As you can see, for a 10-digit prime, the running time is very much reduced:
function isPrimeSqrt(num) {
var max = Math.floor(Math.sqrt(num));
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
return true;
}
function isPrimeHalf(num) {
var max = Math.floor(num / 2);
for (var i = 2; i <= max; i++)
if (num % i === 0) {
return false;
}
return true;
}
let now = Date.now();
const pHalf = isPrimeHalf(1010189899);
console.log("Using 'Half' took:", Date.now() - now, "ms. Is prime:", pHalf);
now = Date.now()
const pSqrt = isPrimeSqrt(1010189899);
console.log("Using 'Sqrt' took:", Date.now() - now, "ms. Is prime:", pSqrt);

Got it!
Simply change this line:
for (var j = min; j <= max; j++) {
to this:
for (var j = parseInt(min); j <= parseInt(max); j++) {
Get familiar with Debugger Tools (F12 in most browsers). There you can pause execution in certain lines and check value and type of variables. If you do it, there you'll see than min = "5", insted of min = 5. That's why 5-49 doesn't work, beacuse "5" is smaller than "49" (beacuse it's first digit is lower), so it doesn't loop at all.

Related

Increment number of attempts and decrement number of guesses remaining

I am new to JS, I want to the code to display number of attempts made, number of guesses remaining in this simple game. I have gotten lost in the code and I don't know what I am not doing right. The const remainingAttempts returns undefined yet I want to subtract number of attempts made from maxNumberOfAttempts.
const guessInput = document.getElementById("guess");
const submitButton = document.getElementById("submit");
const resetButton = document.getElementById("reset");
const messages = document.getElementsByClassName("message");
const tooHighMessage = document.getElementById("too-high");
const tooLowMessage = document.getElementById("too-low");
const maxGuessesMessage = document.getElementById("max-guesses");
const numberOfGuessesMessage = document.getElementById("number-of-guesses");
const correctMessage = document.getElementById("correct");
let targetNumber;
let attempts = 0;
let maxNumberOfAttempts = 5;
// Returns a random number from min (inclusive) to max (exclusive)
// Usage:
// > getRandomNumber(1, 50)
// <- 32
// > getRandomNumber(1, 50)
// <- 11
function getRandomNumber(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function checkGuess() {
// Get value from guess input element
const guess = parseInt(guessInput.value, 10);
attempts = attempts + 1;
hideAllMessages();
if (guess === targetNumber) {
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You made ${attempts} guesses`;
correctMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
if (guess !== targetNumber) {
if (guess < targetNumber) {
tooLowMessage.style.display = "";
} else {
tooHighMessage.style.display = ""; //replaced else condition statement
}
const remainingAttempts = maxNumberOfAttempts - attempts;
numberOfGuessesMessage.style.display = "";
numberOfGuessesMessage.innerHTML = `You guessed ${guess}. <br> ${remainingAttempts} guesses remaining`;
}
if (attempts === maxNumberOfAttempts) {
maxGuessesMessage.style.display = "";
submitButton.disabled = true;
guessInput.disabled = true;
}
guessInput.value = "";
resetButton.style.display = "";
}
function hideAllMessages() {
/*replaced elementIndex <= messages.length to elementIndex < messages.length*/
for (let elementIndex = 0; elementIndex < messages.length; elementIndex++) {
messages[elementIndex].style.display = "none"; //removed [elementIndex]
}
// for (let message in messages.value) {
// //used for..in to iterate through the HTML collection
// message.style.display = "none";
// }
}
function setup() {
// Get random number
targetNumber = getRandomNumber(1, 100);
console.log(`target number: ${targetNumber}`);
// Reset number of attempts
maxNumberOfAttempts = 0;
// Enable the input and submit button
submitButton.disabled = false;
guessInput.disabled = false;
hideAllMessages();
resetButton.style.display = "none";
}
submitButton.addEventListener("click", checkGuess);
resetButton.addEventListener("click", setup);
setup();
main {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
margin: auto;
}
#guess {
width: 5em;
}
#reset {
margin: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="guess.css" rel="stylesheet" />
<title>Number Guesser</title>
</head>
<body>
<main>
<h1>Guessing Game</h1>
<p>
I'm thinking of a number from 1 to 99! Can you guess it in 5 tries or
less?
</p>
<div>
<input type="number" id="guess" min="1" max="99" />
<button id="submit">Submit Guess</button>
</div>
<div>
<p class="message" id="number-of-guesses"></p>
<p class="message" id="too-high">You guessed too high. Try again.</p>
<p class="message" id="too-low">You guessed too low. Try again.</p>
<p class="message" id="max-guesses">
You reached the max number of guesses
</p>
<p class="message" id="correct">
Congratulations, You guessed correctly! <br />
Would you like to play again?
</p>
</div>
<button id="reset">Reset</button>
</main>
<script src="guess.js"></script>
</body>
</html
just increment attempts as attempts++; below const remainingAttempts = maxNumberOfAttempts - attempts;. this should solve the no. of attempts part.
In setup(), when you reset the number of attempts, you should be setting it to 5: maxNumberOfAttempts = 5;
Additionally, in checkGuess(), you should:
Make sure to decrease the number of attempts with each guess. Add maxNumberOfAttempts-- at the top of the function.
At the bottom of if (guess !== targetNumber), you can replace the variable in the message from ${remainingAttempts} to ${maxNumberOfAttempts}
, since maxNumberOfAttempts is now keeping track of the amount of attempts remaining.
Lastly, the next if statement can check if the user is out of attempts with if (maxNumberOfAttempts === 0) {...}
This eliminates the need to use 3 different 'attempt' variables since you're resetting back to '5' at each instance of setup() anyway.

Uncaught SyntaxError: Unexpected end of input false error [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
Just The last "}" shows a error for no reason.
A "}" is a death?
VIIIth attempt.
A coding job makes my brain kinda melt.
Send help! I am freaking out!
Can't fix this.
Return 1;
I am almost losing my mind.
Pot of 1 and 0s'.
Thanks if you read this btw just read the first letter on the first words on start of the sentences.
console.error("1010101 011110 1010101010 1001 0101010100 1001 010001001");
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
console.log(makeid(29));
}
document.getElementById("submit").onclick = function() {
console.log("Submitted prize. Prize ID:");
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
console.log(makeid(27));
}
document.getElementById("acceptpol").onclick = function() {
console.log("Accepted promise. Promise ID:");
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
console.log(makeid(29));
}
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
console.log(makeid(11));
}
h1{
color: green;
}
label{
color: green;
}
input{
color: green;
}
body,html{
height: 100%;
margin: 0;
background-image: url('smile.jpg');
background-position: center;
background-size: cover;
}
<html>
<body>
<h1> Press F12 in your keyboard to see your promise, submit and your contact ID </h1>
<h1> ENTER YOUR INFORMATION TO CLAIM YOUR PRIZE! </h1>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname" id="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<label for="emailadd">E-Mail Address (So we can contact to you):</label>
<input type="text" id="emailadd" name="emailadd"><br><br>
<label for="address">Your Home Address</label>
<input type="text" id="address" name="address"><br><br>
<input type="checkbox" id="acceptpol">accept to contact to us when your prize when it's not in your address</input>
<input id="submit" type="submit" value="Submit"></input>
</body>
<head>
<title> TriviaAwards.com </title>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
</html>
You are missing 2 closing brackets in your javascript you don't close the document.getElementById functions:
document.getElementById("submit").onclick = function() {
console.log("Submitted prize. Prize ID:");
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
console.log(makeid(27));
}
} // add this
Same for the other getElementById function.
If you keep your indentation the same you can prevent these errors.

If statement with OR condition not working

I have no JS or other language background. I have learned everything in the code for this particular problem so bear with me if things aren't clean and clever. I have done a lot of searching before resulting to asking here, so hopefully ALMOST everything is accounted for.
I have a conditional statement I just CANNOT get to run correctly. (entire code for context at the bottom)
if (pyramid < 1 || pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
}
I am most concerned with (pyramid < 1 || pyramid > 8) but if you can help me account for an input value of zero (due to complexities with 0 being false-y), bonus points.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<style id="dennis">
#ahahah {
display: none;
}
</style>
</head>
<body>
<h1>Text Box Input and Output</h1>
<form action="">
<fieldset>
<label>write how tall </label>
<input type="number" id="numberin" min="" max="" step="1" />
<input type="button" value="Make the Pyramid" onclick="makepyramid()" />
</fieldset>
</form>
<script type="text/javascript">
function makepyramid() {
var numberin = document.getElementById("numberin");
var pyramid = numberin.value;
var spaceincrement = numberin.value;
var octoincrement = numberin.value;
var spaces;
var octothorps;
var bringittogether = "";
//WHY YOU NO WORK?! I'd like to make 0 work as well but I am more concerned with the range first.
//first if statement is the ideal, second is bare minimum.
//if (pyramid === null || pyramid < 1 || pyramid > 8) {
//if (pyramid < 1 || pyramid > 8) {
//Put in this if statement to show what SHOULD happen
if (pyramid > 8) {
var dennis = document.getElementById("dennis");
var showdennis = "#ahahah{display: block}";
dennis.appendChild(document.createTextNode(showdennis));
document.getElementById("giza").innerHTML = "";
return;
} else {
document.getElementById("ahahah").innerHTML = "";
//decide how many lines to make
for (var a = 0; a < pyramid; a++) {
//number of spaces loop
for (var b = 1, spaces = ""; b < spaceincrement; b++) {
spaces += "_";
}
//number of octothorps in one line loop
for (var c = pyramid, octothorps = ""; c >= octoincrement; c--) {
octothorps += "#";
}
//print spaces, hashes, 2 spaces, start new line
bringittogether += spaces + octothorps + "__" + octothorps + "<br/>";
document.getElementById("giza").innerHTML = bringittogether;
//increment to change next line's number of spaces (one less) and octothorps (one more)
spaceincrement = [spaceincrement - 1];
octoincrement = [octoincrement - 1];
}
}
}
</script>
<hr />
<div id="giza"></div>
<div id="ahahah">
<p><img src="https://i.imgur.com/1A8Zgnh.gif" /> You must select a number between 1 and 8
</p>
</div>
</body>
</html>

How to make Ulam number sequence in javascript?

I can't figure this problem out, I already checked my code but I don't know what the problem is.
This is the question: A mathematician Ulam proposed generating a sequence of numbers from any positive integer n (n>0) as follows.
if n is 1, it will stop.
if n is even, the next number is n/2.
if n is odd, the next number is 3 * n + 1.
continue with the process until reaching 1.
here some examples for the first few integers.
2->1
3->10->5->16->8->4->2->1
4->2->1
6->3->10->5->16->8->4->2->1
7->22->11->34->17->52->26->13->40->20->10->5->16->8->4->2->1
Sample Run:
Enter Positive Integer: 5
The ulam Number Sequence is : 5->16->8->4->2->1
this is my code...
<!DOCTYPE html>
<html>
<head>
<title>Ulam Number Sequence</title>
</head>
<body>
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="Reset()">Reset</button>
</form>
<p id = "info"> </p>
<script>
function isOdd(num) {
var odd = true;
for (var i = 0; i <= num; i++) {
if (num % i == 0) {
odd = false;
break;
}
}
return odd;
}
function isEven(num) {
var even = true;
for (var i = 0; i <= num; i++) {
if (num % i == 1) {
even = false;
break;
}
}
return even;
}
function process(){
var n = parseInt(document.getElementById("num").value);
var result1 = [];
for(var i = 0; i <= n; i++){
if(isOdd(i)){
result1[result1.length] = i /2;
}
if(isEven(i)){
result1[result1.length] = 3 * i + 1;
}
if(isOdd(result1)){
result1[result1.length] = result1 / 2;
}
if(isEven(result1)){
result1[result1.length] = 3 * result1 +1;
}
//result1[result1.length] = i * 3 + 1;
document.getElementById("info").innerHTML = result1.join("->");
}
}
function Reset(){
document.getElementById("info").innerHTML = "";
document.getElementById("num").value = "" ;
}
</script>
</body>
</html>
Maybe this is a solution for you (and a little hint):
function process() {
var n = parseInt(document.getElementById('num').value),
result = [n];
if (isFinite(n) && n && n === Math.abs(n)) {
while (n !== 1) {
// basically this is all to do.
n = n % 2 ? 3 * n + 1 : n / 2;
result.push(n);
}
document.getElementById("info").innerHTML = result.join(' > ');
} else {
document.getElementById("info").innerHTML = 'Does not compute!';
}
}
function reset() {
document.getElementById('info').innerHTML = '';
document.getElementById('num').value = ''
}
<form name="myform" onsubmit=" return false">
Enter positive integer: <input type="number" id="num" required>
<button onclick="process()">Process</button>
<button onclick="reset()">Reset</button>
</form>
<p id="info"></p>

How to find prime numbers in entered number range [duplicate]

This question already has answers here:
How to find prime numbers between 0 - 100?
(40 answers)
Closed 9 years ago.
I'm just trying to find prime numbers of an entered range of numbers. I have no clue how to calculate finding primes. I need to add them to an array and output the array after. I put a placeholder for the calculation... I just can't seem to figure out how find the primes.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>LeapYears</title>
<script type="text/javascript">
/* <![CDATA[ */
function calcPrimeNumber(){
var beginNum = document.numbers.firstNum.value;
var endNum = document.numbers.secondNum.value;
var primeNumbs = new Array();
var ctr = 0;
while (beginNum <= endNum){ //throwaway
if ((beginNum % beginNum == 0) && (beginNum % 1 == 0)){
primeNumbs[ctr] = beginNum;
++ctr;
}
++beginNum;
}
if (primeNumbs == 0){
window.alert("There were no leap years within the range.");
}
else {
outputPrimeNums(primeNumbs);
}
}
function outputPrimeNums(primes){
document.write("<h2>Prime Numbers</h2>");
for (i=0;i<primes.length;i++){
document.write(primes[i] + "<br/>");
}
}
/* ]]> */
</script>
</head>
<body>
<form name="numbers">
Beginning Number: <input type="text" name="firstNum" /> End Number: <input type="text" name="secondNum" />
<input type="button" value="Find Prime Numbers" onclick="calcPrimeNumber()" />
</form>
</body>
</html>
try this full page of prime no example
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>LeapYears</title>
<script type="text/javascript">
/* <![CDATA[ */
function calcPrimeNumber(){
var beginNum = parseInt(document.numbers.firstNum.value);
var endNum = parseInt(document.numbers.secondNum.value);
var primeNumbs = new Array();
var ctr = beginNum;
while(ctr<=endNum)
{
if(isPrime(ctr)==true)
{
primeNumbs[primeNumbs.length] = ctr;
}
ctr = ctr+1;
}
if (primeNumbs.length == 0){
document.getElementById('output_content').innerHTML = "There were no prime no within the range.";
}
else {
outputPrimeNums(primeNumbs);
}
}
function isPrime(num)
{
var flag = true;
for(var i=2; i<=Math.ceil(num/2); i++)
{
if((num%i)==0)
{
flag = false;
break;
}
}
return flag;
}
function outputPrimeNums(primes){
var html = "<h2>Prime Numbers</h2>";
for (i=0;i<primes.length;i++){
html += primes[i] + "<br/>";
}
document.getElementById('output_content').innerHTML = html;
}
/* ]]> */
</script>
</head>
<body>
<form name="numbers">
Beginning Number: <input type="text" name="firstNum" /> End Number: <input type="text" name="secondNum" />
<input type="button" value="Find Prime Numbers" onclick="calcPrimeNumber()" />
</form>
<div id="output_content">
</div>
</body>
</html>
You should use some algorithm to check whether a given no is prime no or not inside while loop .
http://en.wikipedia.org/wiki/Prime_number
http://en.wikibooks.org/wiki/Efficient_Prime_Number_Generating_Algorithms
You need two loops here - the first to run between beginNum and endNum and the second to run from 1 to beginNum for each value of beginNum in the outer loop.
Try replacing the main section of your code with the following. (For clarity, I'm going to introduce a new variable - numberBeingTested.)
var ctr = 0;
var numberBeingTested = beginNum;
while (numberBeingTested <= endNum){ //throwaway
var testDivisor = 2;
var isPrime = true;
while (testDivisor < numberBeingTested ){ //throwaway
if (numberBeingTested % testDivisor == 0) {
isPrime = false;
}
++testDivisor;
}
if (isPrime){
primeNumbs[ctr] = numberBeingTested;
++ctr;
}
++numberBeingTested;
}
Note that there are many possible improvements here - for a start, this code as it stands will tell you that 1 is prime, and there are significant possible performance improvements (such as testing possible divisors up to the square root of the number being tested rather than the number itself) - but for your purposes it will probably suffice.
What I try was to edit Sieve of Atkin algorithm from linked question:
function getPrimes(min, max) {
var sieve = [], i, j, primes = [];
for (i = 2; i <= max; ++i) {
if (!sieve[i]) {
// i has not been marked -- it is prime
if (i >= min) {
primes.push(i);
}
for (j = i << 1; j <= max; j += i) {
sieve[j] = true;
}
}
}
return primes;
}
console.log(getPrimes(10, 100));
This will give you array with prime numbers from min to max. It still has to go through all number from 2, so maybe there will be more effective way how to achieve this.

Categories