JSFiddle - React, Tailwind, and code Playground
HTML
<div id="output"></div>
JavaScript
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
function isPrime(num) {
//-n, 0, 1 not allowed
if (num < 2) return false;
//check for single digit primes
if (inArray(num, [2, 3, 5, 7])) return true;
//prime numbers end in 1, 3, 7 or 9 no matter how long they are
if (!inArray(String(num).substr(-1), [1, 3, 7, 9])) return false;
//if the number is divisible by 3 or 7 (very common) then it's not prime
if (num % 3 == 0 || num % 7 == 0) return false;
/*
* Now find all the numbers up to the square root of potential prime
* number and test if they divide into it
*/
//the primes array holds prime numbers to test if they divide into num
var primes = [2, 3, 5, 7];
var limit = Math.sqrt(num);
for (var i = 11; i <= limit; i++) {
//if the number is divisible by a prime number then it's not prime
var isPrime = true;
for(var t = 0; t < primes; t++) {
if (i % primes[t] == 0) {
isPrime = false;
break;
}
}
//check if the increment goes into our number
if (isPrime) {
if (num % i == 0) return false;
primes.push(i);
}
}
//num is prime - divisible by itself and 1 only
return true;
}
function start() {
var max = 100;
for (i = 2; i <= max; i++) {
if(isPrime(i)) {
console.log(i, "is a prime number");
document.getElementById("output").innerHTML = i;
}
}
}
start();