Check Number prime in JavaScript

Check Number prime in JavaScript

let inputValue= 7;
let isprime=inputValue==1? false:true;  //bcoz 1 is not prime


for(let i=2;i<inputValue;i++){
inputValue%i==0? isprime*=false :isprime*=true;
};


alert(`${inputValue} is ${isprime? 'prime':'not prime'} number`);

336613 次浏览
function isPrime(num) {
var prime = num != 1;
for(var i=2; i<num; i++) {
if(num % i == 0) {
prime = false;
break;
}
}
return prime;
}

DEMO

A small suggestion here, why do you want to run the loop for whole n numbers?

If a number is prime it will have 2 factors (1 and number itself). If it's not a prime they will have 1, number itself and more, you need not run the loop till the number, may be you can consider running it till the square root of the number.

You can either do it by euler's prime logic. Check following snippet:

function isPrime(num) {
var sqrtnum=Math.floor(Math.sqrt(num));
var prime = num != 1;
for(var i=2; i<sqrtnum+1; i++) { // sqrtnum+1
if(num % i == 0) {
prime = false;
break;
}
}
return prime;
}

Now the complexity is O(sqrt(n))

For more information Why do we check up to the square root of a prime number to determine if it is prime?

Hope it helps

You are trying to check too much conditions. just one loop is required to check for a prime no.

function isPrime(num){
if(num==2)
return true;
for(i=2;i<Math.sqrt(num);i++) // mathematical property-no number has both of its factors greater than the square root
{
if(num % i==0)
return false; // otherwise it's a prime no.
}
return true;
}

You have to consider every no. a prime no. unless it is divisible by some no. less than or equal to the square root.

Your solution has got a return statement for every case,thus it stops execution before it should.It doesn't check any number more than once.It gives wrong answer for multiple cases-- 15,35.. in fact for every no. that is odd.

Time complexity: O(sqrt(n))

Space complexity: O(1)

const isPrime = num => {
for(let i = 2, s = Math.sqrt(num); i <= s; i++)
if(num % i === 0) return false;
return num > 1;
}

It looks like your first if statement within the first 'if' statement within the for loop. Since if num = 9 and i = 2, 9 % i !== 0 but 9 is not prime since on the next iteration where i = 3, 9 % i === 0.

Here would be my answer to that question.

var isPrime = function(n) {
if(typeof n !== 'number' || n <= 1 || n % 1 !== 0){
return false;
}
for(var i = 2; i <= Math.sqrt(n); i += 1){
if(n % i === 0){
return false;
}
}
return true;
};

The first if statement catches the edge cases. The for loop then checks from 2 up to the square root of n because of the mathematical property where no number has both of its factors greater than the square root of that number.

Hope this helps!

This one is I think more efficient to check prime number :

function prime(num){
if(num == 1) return true;
var t = num / 2;
var k = 2;
while(k <= t) {
if(num % k == 0) {
return false
} else {
k++;
}
}
return true;
}
console.log(prime(37))

you can use below code in javascript for checking number is prime or not. It will reduce no of iteration and get the result fast.

function testPrime(num) {
var isPrime = true;
if (num >= 2) {
if(num == 2 || num == 3){
isPrime = true;
}
else if (num % 2 == 0) {
isPrime = false;
}
else {
for (i = 3; i <= Math.floor(Math.sqrt(num)); i += 2) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
}
else {
isPrime = false;
}
return isPrime;
}

//testPrime(21) false

function isPrimeNumber(n) {
for (var i = 2; i < n; i++) { // i will always be less than the parameter so the condition below will never allow parameter to be divisible by itself ex. (7 % 7 = 0) which would return true
if(n % i === 0) return false; // when parameter is divisible by i, it's not a prime number so return false
}
return n > 1; // otherwise it's a prime number so return true (it also must be greater than 1, reason for the n > 1 instead of true)
}


console.log(isPrimeNumber(1));  // returns false
console.log(isPrimeNumber(2));  // returns true
console.log(isPrimeNumber(9));  // returns false
console.log(isPrimeNumber(11)); // returns true

// A list prime numbers


function* Prime(number) {
const infinit = !number && number !== 0;
const re = /^.?$|^(..+?)\1+$/;
let actual = 1;
 

while (infinit || number-- ) {
if(!re.test('1'.repeat(actual)) == true) yield actual;
actual++
};
};


let [...primers] = Prime(101); //Example
console.log(primers);

This will cover all the possibility of a prime number . (order of the last 3 if statements is important)

   function isPrime(num){
if (num==0 || num==1) return false;
if (num==2 || num==3 ) return true;
if (num % Math.sqrt(num)==0 ) return false;
for (let i=2;i< Math.floor(Math.sqrt(num));i++) if ( num % i==0 ) return false;
if ((num * num - 1) % 24 == 0) return true;
}

Simple version:

function isPrime(num) {
if (num <= 1) {
return false;
} else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}


console.log(isPrime(9));

Cool version:

const isPrime = n => ![...Array(n).keys()].slice(2).map(i => !(n%i)).includes(true) && ![0,1].includes(n)

This is how I'd do it:

function isPrime(num) {
if(num < 2) return false;
if(num == 2) return true;
for(var i = 2; i < num; i++) {
if(num % i === 0) return false;
}
return true;
}

very simple

const isPrime = num => {
for (var i = 2; i < num; i++) if (num % i == 0) return false;
return num >= 2;
}
(function(value){
var primeArray = [];
for(var i = 2; i <= value; i++){
if((i === 2) || (i === 3) || (i === 5) || (i === 7)){
primeArray.push(i);
}
else if((i % 2 !== 0) && (i % 3 !== 0) && (i % 5 !== 0) && (i % 7 !== 0)){
primeArray.push(i);
}
}
console.log(primeArray);
}(100));

I think a better way to find a prime number is with this logic:

var p=prompt("input numeric value","10"); // input your number
for(j=2;j<p;j++){
if(isPrimes(j)){
document.write(j+", "); // for output the value
} // end if
}// end for loop
function isPrimes(n) {
var primes = true;// let prime is true
for (i=2;i<n;i++) {
if(n%i==0) {
primes= false; // return prime is false
break; // break the loop
}// end if inner
}// end inner loop
return primes; // return the prime true or false
}// end the function

function isPrime(num) { // returns boolean
if (num <= 1) return false; // negatives
if (num % 2 == 0 && num > 2) return false; // even numbers
const s = Math.sqrt(num); // store the square to loop faster
for(let i = 3; i <= s; i += 2) { // start from 3, stop at the square, increment in twos
if(num % i === 0) return false; // modulo shows a divisor was found
}
return true;
}
console.log(isPrime(121));

Thanks to Zeph for fixing my mistakes.

Following code uses most efficient way of looping to check if a given number is prime.

function checkPrime(number){
if (number==2 || number==3) {
return true
}
if(number<2 ||number % 2===0){
return false
}
else{
for (let index = 3; index <= Math.sqrt(number); index=index+2) {
if (number%index===0) {
return false
}
}
}
return true
}
  1. First check rules out 2 and lesser numbers and all even numbers
  2. Using Math.sqrt() to minimize the looping count
  3. Incrementing loop counter by 2, skipping all even numbers, further reducing loop count by half
function isAPrimeNumber(num){
var counter = 0;
//loop will go k equals to $num
for (k = 1; k <= num; k++) {
//check if the num is divisible by itself and 1
// `%` modulus gives the reminder of the value, so if it gives the reminder `0` then it is divisible by the value
if (num % k == 0) {
//increment counter value 1
counter  = counter  + 1;
}
}
//if the value of the `counter is 2` then it is a `prime number`
//A prime number is exactly divisible by 2 times only (itself and 1)
if (counter == 2) {
return num + ' is a Prime Number';
}else{
return num + ' is nota Prime Number';
}
}

Now call isAPrimeNumber() function by passing a value.

var resp = isAPrimeNumber(5);
console.log(resp);

Output:

5 is a Prime Number
function isPrime(num) {
if(num < 2) return false;
for (var i = 2; i <= num/2; i++) {
if(num%i==0)
return false;
}
return true;
}

If we want the prime number between two number we have to add this code only

for(var i = 0; i < 100; i++){
if(isPrime(i))
console.log(i);
}

I think this question is lacking a recursive solution:

// Preliminary screen to save our beloved CPUs from unneccessary labour


const isPrime = n => {
if (n === 2 || n === 3) return true;
if (n < 2 || n % 2 === 0) return false;


return isPrimeRecursive(n);
}


// The recursive function itself, tail-call optimized.
// Iterate only over odd divisors (there's no point to iterate over even ones).
 

const isPrimeRecursive = (n, i = 3, limit = Math.floor(Math.sqrt(n))) => {
if (n % i === 0) return false;
if (i >= limit) return true; // Heureka, we have a prime here!
return isPrimeRecursive(n, i += 2, limit);
}


// Usage example


for (i = 0; i <= 50; i++) {
console.log(`${i} is ${isPrime(i) ? `a` : `not a` } prime`);
}

This approach have it's downside – since browser engines are (written 11/2018) still not TC optimized, you'd probably get a literal stack overflow error if testing primes in order of tens lower hundreds of millions or higher (may vary, depends on an actual browser and free memory).

Using Ticked solution Ihor Sakaylyuk

const isPrime = num => {
for(let i = 2, s = Math.sqrt(num); i <= s; i++)
if(num % i === 0) return false;
return num !== 1 && num !== 0;
}

Gives in console

isPrime( -100 ) true

const isPrime = num => {
// if not is_number num return false


if (num < 2) return false


for(let i = 2, s = Math.sqrt(num); i <= s; i++) {
if(num % i === 0) return false
}


return true
}

Gives in console

isPrime( 1 ) false

isPrime( 100 ) false

isPrime( -100 ) false

First 6 primes ? 2 3 5 7 11 13 ?

isPrime( 1 ) false

isPrime( 2 ) true // Prime 1

isPrime( 3 ) true // Prime 2

isPrime( 4 ) false

isPrime( 5 ) true // Prime 3

isPrime( 6 ) false

isPrime( 7 ) true // Prime 4

isPrime( 8 ) false

isPrime( 9 ) false

isPrime( 10 ) false

isPrime( 11 ) true // Prime 5

isPrime( 12 ) false

isPrime( 13 ) true // Prime 6

You can try this one

function isPrime(num){
   	

// Less than or equal to 1 are not prime
if (num<=1) return false;
    

// 2 and 3 are prime, so no calculations
if (num==2 || num==3 ) return true;
    

// If mod with square root is zero then its not prime
if (num % Math.sqrt(num)==0 ) return false;
    

// Run loop till square root
for(let i = 2, sqrt = Math.sqrt(num); i <= sqrt; i++) {
    

// If mod is zero then its not prime
if(num % i === 0) return false;
}
    

// Otherwise the number is prime
return true;
}
   

   

for(let i=-2; i <= 35; i++) {
console.log(`${i} is${isPrime(i) ? '' : ' not'} prime`);
}

Prime numbers are of the form 6f ± 1, excluding 2 and 3 where f is any integer

 function isPrime(number)
{
 if (number <= 1)
return false;


// The check for the number 2 and 3
if (number <= 3)
return true;


if (number%2 == 0 || number%3 == 0)
return false;


for (var i=5; i*i<=number; i=i+6)
{
if (number%i == 0 || number%(i+2) == 0)
 return false;
}


return true;
}

Time Complexity of the solution: O(sqrt(n))

This answer is based on the answer by Ihor Sakaylyuk. But instead of checking for all numbers, I am checking only the odd numbers. Doing so I reduced the time complexity of the solution to O(sqrt(n)/2).

function isPrime(num) {
if (num > 2 && num % 2 === 0) return false;
for (var i = 3; i < Math.sqrt(num); i += 2) {
if (num % i === 0) return false;
}
return num > 1;
}

function isPrime(n){
if (isNaN(n) || !isFinite(n) || !Number.isInteger(n) || n<2) {
return false;
}


if (n%2==0){
return (n==2);
}


var sqrt = Math.sqrt(n);
for (var i = 3; i < sqrt; i+=2) {
if(n%i == 0){
return false;
}
}
    

return true;
}

One of the shortest version

isPrime=(n)=>[...Array(n-2)].map((_,i)=>i+2).filter(i=>n%i==0).length==0

Why are you trying to use loops!? Iterating is such a waste of computing power here...

This can be done using math:

function isPrime(num) {
if ( num !=1 && num%3 != 0 && num%5 != 0 && num%7 != 0 && num%9 != 0 && num%11 != 0 && Math.sign(num) == 1 && Math.round(num) == num) {


if ( (num-1)%6 == 0 || (num+1)%6 == 0 ) {
return true;
}


} // no need for else statement since if true, then will do return
return num==11||x==9||num==5||num==3||num==2; // will return T/F;
}

Steps:

  1. Check if the number is divisible by 5 (evenly)
  2. Check if the number is positive (negative numbers are not prime)
  3. Check if the number is a whole number (5.236 by rule not prime)
  4. Check if the number ± 1 is divisible by 6 (evenly)
    For more information check out 3Blue1Brown's Video
  5. Check if the number is 2, 3, 9 or 11 (outliers with the rule)
  6. Check if the number is 7 or 5 (due to attempt at false-positive reduction)

Always try to do the mathematical way, rather than iterating over loops. Math is almost always the most efficient way to do something. Yes, this equation might be confusing... However, we don't need much readability when it comes to checking if something is prime or not... It likely isn't going to need to be maintained by future code editors.

EDIT:
Optimized code version:

function isPrime(x=0) {
const m = Math;
return (x%3!=0&&x%5!=0&&x%7!=0&&x%9!=0&&x%11!=0&&x!=1&&m.sign(x)*m.round(x)==x&&(!!!((x-1)%6)||!!!((x+1)%6)))||x==11||x==9||x==7||x==5||x==3||x==2;
}

EDIT:
As it turns out... there's more to do with false-positive detection, because they're randomly distributed (at least seemingly) so the +-1 %6 stuff really isn't going to work for everything... But I'm definitely on to something here...

My Solution,

function isPrimeNumber(number){
if(number <= 1) return false;
if(number <= 3) return true;
for(let i = 2; i < 9; i++) {
if(number === i) continue;
if(number % i === 0 ) return false;
}
return true;
}


for(let i = 0; i <= 100; i++){
if (isPrimeNumber(i)) console.log(i);
}

The only even prime number is 2, so we should exclude even numbers from the loop.

function isPrime(a) {
if (a < 2) return false;
if (a > 2) {
if (a % 2 == 0) return false;
for (let x = 3; x <= Math.sqrt(a); x += 2) {
if (a % x == 0) return false;
}
}
return true;
}

Since Node.js 16, this is built-in:

import {checkPrimeSync as isPrime} from 'node:crypto';


console.log(isPrime(13));
//=> true

Otherwise, @IhorSakaylyuk's answer can be improved further by skipping even numbers:

function isPrime(number) {
if((number % 2 === 0 && number !== 2) || number <= 1) {
return false;
}


const limit = Math.floor(Math.sqrt(number));


for(let index = 3; index <= limit; index += 2) {
if (number % index === 0) {
return false;
}
}


return true;
}

I also created a npm package with this function.

I would do it like this:

const isPrime = (num) => num < 10 ? [2, 3, 5, 7].includes(num) : ![2, 3, 5, 7].some(i => !(num % i));

UPDATE (thx to @lakscastro):

export const isPrime = n => n <= 1 ? false : !Array.from(new Array(n), (el, i) => i + 1)
.filter(x => x > 1 && x < n)
.find(x => n % x === 0);

Might be useful for some people: An implementation of the Miller Rabin primality test. Works for all positive integers less than Number.MAX_SAFE_INTEGER.

Try on JSFiddle: https://jsfiddle.net/4rxhas2o/


let unsafeToSquare = Math.floor(Math.sqrt(Number.MAX_SAFE_INTEGER))


function addMod(a, b, m) {
// Returns (a + b) % m


let sum = a + b


let result = sum % m


if (sum < Number.MAX_SAFE_INTEGER)
return result


let signature = ((a % 8) + (b % 8)) % 8


let sumMod = sum % 8


for (let i = -2; i <= 2; ++i) {
if ((sumMod + i) % 8 === signature) {
let ret = result + i


if (ret > m)
ret = (result - m) + i // prevent overflow


return ret
}
}
}


function mulMod(a, b, m) {
if (m === 0)
return 0


let prod = a * b


if (prod < Number.MAX_SAFE_INTEGER)
return prod % m


let y = 0
let result = a


while (b > 1) {
if (b % 2 === 0) {
result = addMod(result, result, m)


b /= 2
} else {
y = addMod(result, y, m)
result = addMod(result, result, m)


b = (b - 1) / 2
}
}


return addMod(result, y, m)
}


function squareMod(b, m) {
// Computes (b * b % m)


return mulMod(b, b, m)
}


function expModLargeB(b, exponent, m) {
let y = 1


while (exponent > 1) {
if (exponent % 2 === 0) {
b = squareMod(b, m)


exponent /= 2
} else {
y = mulMod(y, b, m)
b = squareMod(b, m)


exponent = (exponent - 1) / 2
}
}


return mulMod(b, y, m)
}


function expMod(b, exponent, m) {
if (exponent === 0)
return 1


if (b >= unsafeToSquare || m >= unsafeToSquare) {
return expModLargeB(b, exponent, m)
}


let y = 1


while (exponent > 1) {
if (exponent % 2 === 0) {
b *= b
b %= m


exponent /= 2
} else {
y *= b
b *= b


y %= m
b %= m


exponent = (exponent - 1) / 2
}
}


return (b * y) % m
}


function _isProbablePrimeMillerRabin(p, base=2) {
let pm1 = p - 1
let pm1div = pm1
let d, r = 0


while (true) {
if (pm1div % 2 === 0) {
pm1div /= 2


r++
} else {
d = pm1div
break
}
}


let x = expMod(base, d, p)


if (x === 1 || x === pm1)
return true


for (let i = 0; i < r - 1; ++i) {
x = squareMod(x, p)


if (x === pm1)
return true
}


return false
}


function _isPrimeLarge(p) {
let bases


if (p < 2047)
bases = [2]
else if (p < 1373653)
bases = [2, 3]
else if (p < 9080191)
bases = [31, 73]
else if (p < 25326001)
bases = [2, 3, 5]
else if (p < 3215031751)
bases = [2, 3, 5, 7]
else if (p < 4759123141)
bases = [2, 7, 61]
else if (p < 1122004669633)
bases = [2, 13, 23, 1662803]
else if (p < 2152302898747)
bases = [2, 3, 5, 7, 11]
else if (p < 3474749660383)
bases = [2, 3, 5, 7, 11, 13]
else if (p < 341550071728321)
bases = [2, 3, 5, 7, 11, 13, 17]
else
bases = [2, 3, 5, 7, 11, 13, 17, 19, 23]




return bases.every(base => _isProbablePrimeMillerRabin(p, base))
}


let smallPrimes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223]


function isPrime(p) {
if (!Number.isInteger(p) || p < 2)
return false


// Test for small primes
for (let i = 0; i < smallPrimes.length; ++i) {
let prime = smallPrimes[i]


if (p === prime)
return true
if (p % prime === 0)
return false
}


if (p <= 49729) { // 223*223
return true;
}
else {
return _isPrimeLarge(p)
}
}




const tests = [1, 2, 3, 10, 100, 100019, 10000000019, 100000000003, 10000000000037]
let start = performance.now()


tests.forEach(test => {
console.log(`${test} is ${ isPrime(test) ? "" : "not " }prime`)
})


let end = performance.now()
console.log("Tests completed in " + (end - start) + " ms.")

This calculates square differently and skips even numbers.

const isPrime = (n) => {
if (n <= 1) return false;
if (n === 2) return true;
if (n % 2 === 0) return false;
//goto square root of number
for (let i = 3, s = n ** 0.5; i < s; i += 2) {
if (n % i == 0) return false;
}
return true;
};

i think the easiest way to get it and faster is

function isPrime(num) {
for(var i = 2; i < Math.sqrt(num); i++) {
if(num % i === 0){
return false;
}
return num > 1;
}
}


console.log(isPrime(9))

This is a more reliable solution if you want to find n prime numbers.

function findPrime(n) {
const primes = [];
loop1:
for (let j = 0; primes.length < n; j++) {
loop2:
for(let i = 2; i < j; i++){
if(j % i === 0){
continue loop1;
}
}
if(j>1) primes.push(j);
}
console.log(primes);
}
     

findPrime(5);

function isPrime(num) {
return Array.from({ length: num }, (i, index) => index + 1).filter(
(item, i) => (num % item) === 0).length === 2;
}


console.log(isPrime(1)); // false
console.log(isPrime(2)); // true
console.log(isPrime(3)); // true
console.log(isPrime(4)); // false

Here is an optimized solution to prevent loop through all the range number.

  function isPrime(num) {
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0)
return false;
}
return true;
}

Three times faster then regular method:

function isPrime (num){
if (num === 1){
return false;
}
if(num === 2 || num === 3){
return true;
}
if((num % 2 !== 0) && (num % 3 !== 0)){
let k = 1;
const numSqrt = Math.sqrt(num);
if(( 6 * k - 1 ) > numSqrt){
return true;
} else {
while( ( 6 * k - 1 ) <= numSqrt ){
if(num % (6 * k - 1) !== 0 && num % (6 * k + 1) !== 0){
return true;
}
k++;
}
return false;
}
}
return false;
}
console.log(isPrime(29))


We can find prime number up to n with only one loop, also I am increasing loop by +2:

function primeNumber(n) {
let arr = [];
if (n <= 1) return false;
if (n === 2) return true;
let flag = true;
for (let i = 3; i < n; i += 2) {
if (n % i == 0) {
flag = false;
break;
}
}
return flag;
}
// It will retrun bollean true/false
// primeNumber(11)  true
// primeNumber(12)  false

Best part is complexity would be o(n/2)

const checkPrime=(no)=>{
var divisor = 2;


while (no > divisor){
if(no % divisor == 0){
return `${no} is not a  prime no`;
}
else
divisor++;
}
return `${no} is a prime no`;
}
(console.log(checkPrime(3)));
(console.log(checkPrime(12)));
(console.log(checkPrime(233)));

If x is not a prime, then we can find "a" and "b" such that
a**2 <= x <= b**2 , where a,b ∈ N+
=> a <= sqrt(x) <= b
So check until the sqrt(x) its upper bound is enough.

isPrime = x => {
if (!Number.isInteger(x)) return false


if (x > 2 && x % 2 ===0) return false


for (let divisor=3; divisor<=Math.sqrt(x); ++divisor) {
if (x % divisor === 0) return false
}
return x > 1
}


testData = [-1, 0, 1, 2, 3, 4, 4.1, 9, 11, "a"]
for (const data of testData) {
console.log(`${data} is Prime? ${isPrime(data)}`)
}

The following implementation is faster than in all the previous answers, that's why I'm adding it.

The code below is from my prime library:

/**
* Maximum prime number that can be generated in JavaScript,
* using the standard 'number' type (53-bit of integer range).
*/
const maxPrime = 9_007_199_254_740_881;


const dividers = [
0, 2, 6, 8, 12, 18, 20, 26, 30, 32, 36, 42, 48, 50, 56, 60, 62, 68, 72,
78, 86, 90, 92, 96, 98, 102, 110, 116, 120, 126, 128, 132, 138, 140, 146,
152, 156, 158, 162, 168, 170, 176, 180, 182, 186, 188, 198, 200
];


function isPrime(x: number): boolean {
if (isNaN(x) || x < 2 || x > maxPrime || x % 1) {
return false;
}
if (x % 2 === 0) return x === 2;
if (x % 3 === 0) return x === 3;
if (x % 5 === 0) return x === 5;
if (x % 7 === 0) return x === 7;
const m = Math.sqrt(x);
for (let i = 11; i <= m; i += 210) {
for (const a of dividers) {
if (x % (i + a) === 0) {
return i + a === x;
}
}
}
return true;
}

On my machine, it can verify the first million numbers in 217ms.

this is a simple way i hope it helps :)

function isPrime(n) {
if (n <= 1) return false;
if (n === 2) return true;
if (n % 2 === 0) return false;


let arrayDis = [];


for (let i = 1; i <= n; i++) {
let count = n/i;
if (Number.isInteger(count)) arrayDis.push(count);
}
      

if(arrayDis.length > 2) return false
        

return true;
}


console.log(isPrime(121)); // false

BEST SOLUTION

I an unsure if I understand the concept of Time complexity: O(sqrt(n)) and Space complexity: O(1) in this context but the function prime(n) is probably the fastest way (least iterations) to calculate if a number is prime number of any size.

https://github.com/ganeshkbhat/fastprimenumbers, https://www.npmjs.com/package/fast-prime

This probably is the BEST solution in the internet as of today 11th March 2022. Feedback and usage is welcome.

This same code can be applied in any languages like C, C++, Go Lang, Java, .NET, Python, Rust, etc with the same logic and have performance benefits. It is pretty fast. I have not seen this implemented before and has been indigenously done.

If you are looking at the speed and performance here is the """BEST""" hopeful solution I can give:

Max iterations 16666 for n == 100000 instead of 100000 of conventional way

The codes can also be found here: https://github.com/ganeshkbhat/fastprimecalculations

If you use it for your project please spend 2 minutes of your time crediting me by letting me know by either sending me an email, or logging an Github issue with subject heading [User], or star my Github project. But let me know here https://github.com/ganeshkbhat/fastprimecalculations. I would love to know the fans and users of the code logic

function prime(n) {
if ((n === 2 || n === 3 || n === 5 || n === 7)) {
return true
}
if (n === 1 || ((n > 7) && (n % 5 == 0 || n % 7 == 0 || n % 2 == 0 || n % 3 == 0))) {
return false
}
if ((Number.isInteger(((n - 1) / 6))) || (Number.isInteger((n + 1) / 6))) {
for (let i = 1; i < n; i++) {
let factorsix = (i * 6)
let five = n / (5 + factorsix), seven = n / (7 + factorsix)
if (((five > 1) && Number.isInteger(five)) || ((seven > 1) && (Number.isInteger(seven)))) {
return false;
}
if (factorsix > n) {
break;
}
}
return true
}
return false
}

Here is an analysis of all the ways of calculation:

Conventional way of checking for prime:

function isPrimeConventionalWay(n) {
count = 0
// Corner case
if (n <= 1)
return false;
// Check from 2 to n-1
// Max iterations 99998 for n == 100000
for (let i = 2; i < n; i++) {
// Counting Iterations
count += 1
if (n % i == 0) {
console.log("count: Prime Conventional way", count)
return false;
}
}
console.log("count: Prime Conventional way", count)
return true;
}

SQUAREROOT way of checking for prime:

function isPrimeSquareRootWay(num) {
count = 0
// if not is_number num return false
if (num < 2) {
console.log("count: Prime Squareroot way", count)
return false
}


for (let i = 2, s = Math.sqrt(num); i <= s; i++) {
// Counting Iterations
count += 1
if (num % i === 0) {
console.log("count: Prime Squareroot way", count)
return false
}
}
console.log("count: Prime Squareroot way", count)
return true
}

SUGGESTED way of checking for prime:

function prime(n) {
let count = 0
if ((n === 2 || n === 3 || n === 5 || n === 7)) {
// console.log("count: Prime Unconventional way", count)
return true
}
if (n === 1 || ((n > 7) && (n % 5 == 0 || n % 7 == 0 || n % 2 == 0 || n % 3 == 0))) {
// console.log("count: Prime Unconventional way", count)
return false
}
if ((Number.isInteger(((n - 1) / 6))) || (Number.isInteger((n + 1) / 6))) {
for (let i = 1; i < n; i++) {
// Counting Iterations
count += 1
let factorsix = (i * 6)
let five = n / (5 + factorsix), seven = n / (7 + factorsix)
if (((five > 1) && Number.isInteger(five)) || ((seven > 1) && (Number.isInteger(seven)))) {
// console.log("count: Prime Unconventional way", count)
return false;
}
if (factorsix > n) {
// Max iterations 16666 for n == 100000 instead of 100000
break;
}
}
// console.log("count: Prime Unconventional way", count)
return true
}
// console.log("count: Prime Unconventional way", count)
return false
}
    

Tests to compare with the traditional way of checking for prime numbers.

    function test_primecalculations() {
let count = 0, iterations = 100000;
let arr = [];
for (let i = 1; i <= iterations; i++) {
let traditional = isPrimeConventionalWay(i), newer = prime(i);
if (traditional == newer) {
count = count + 1
} else {
arr.push([traditional, newer, i])
}
}
console.log("[count, iterations, arr] list: ", count, iterations, arr)
if (count === iterations) {
return true;
}
return false;
}
        

console.log("Tests Passed: ", test_primecalculations())
    

    

You will see the results of count of number of iterations as below for check of prime number: 100007:

console.log("Is Prime 100007: ", isPrimeConventionalWay(100007))
console.log("Is Prime 100007: ", isPrimeSquareRootWay(100007))
console.log("Is Prime 100007: ", prime(100007))
count: Prime Conventional way 96
Is Prime 100007:  false
count: Prime Squareroot way 96
Is Prime 100007:  false
count: Prime Unconventional way 15
Is Prime 100007:  false

Performance Tests:

let iterations = 1000000;
let isPrimeConventionalWayArr = [], isPrimeSquarerootWayArr = [], primeArr = [], isprimeAKSWayArr = []
let performance = require('perf_hooks').performance;
// let performance = window.performance;


function tests_performance_isPrimeConventionalWayArr(){
for (let i = 1; i <= iterations; i++){
let start = performance.now()
isPrimeConventionalWay(30000239)
let end = performance.now()
isPrimeConventionalWayArr.push(end - start)
}
}
tests_performance_isPrimeConventionalWayArr()


function tests_performance_isPrimeSquarerootWayArr(){
for (let i = 1; i <= iterations; i++){
let start = performance.now()
isPrimeSquarerootWay(30000239)
let end = performance.now()
isPrimeSquarerootWayArr.push(end - start)
}
}
tests_performance_isPrimeSquarerootWayArr()


function tests_performance_primeArr(){
for (let i = 1; i <= iterations; i++){
let start = performance.now()
prime(30000239)
let end = performance.now()
primeArr.push(end - start)
}
}
tests_performance_primeArr()




function calculateAverage(array) {
var total = 0;
var count = 0;
array.forEach(function(item, index) {
total += item;
count++;
});
return total / count;
}


console.log("isPrimeConventionalWayArr: ", calculateAverage(isPrimeConventionalWayArr))
console.log("isPrimeSquarerootWayArr: ", calculateAverage(isPrimeSquarerootWayArr))
console.log("primeArr (suggested): ", calculateAverage(primeArr))

Sample 1 Million Iterations

Iteration 1:

isPrimeConventionalWayArr:  0.00011065770072489977
isPrimeSquarerootWayArr:  0.0001288754000402987
primeArr (suggested):  0.00005511959937214852
isPrimeSquarerootWayTwoArr:  0.00010504549999162554

Iteration 2:

isPrimeConventionalWayArr:  0.00011061320009082556
isPrimeSquarerootWayArr:  0.00012810260016098618
primeArr (suggested):  0.00005620509984344244
isPrimeSquarerootWayTwoArr:  0.00010411459982022643

Iteration 3:

isPrimeConventionalWayArr:  0.00010952920047193766
isPrimeSquarerootWayArr:  0.0001286292002275586
primeArr (suggested):  0.00005520999948307872
isPrimeSquarerootWayTwoArr:  0.00010410030033439397

Iteration 4:

isPrimeConventionalWayArr:  0.00011091169972717762
isPrimeSquarerootWayArr:  0.00012648080018162728
primeArr (suggested):  0.00005570890004560351
isPrimeSquarerootWayTwoArr:  0.00010492690009251237

Iteration 5:

isPrimeConventionalWayArr:  0.00010998740004003048
isPrimeSquarerootWayArr:  0.00012748069976270199
primeArr (suggested):  0.000060324400294572114
isPrimeSquarerootWayTwoArr:  0.00010445670029893518

Iteration 6:

isPrimeConventionalWayArr:  0.00011286130072548985
isPrimeSquarerootWayArr:  0.00012876759915798902
primeArr (suggested):  0.00005682649992406368
isPrimeSquarerootWayTwoArr:  0.0001073473998978734

Iteration 7:

isPrimeConventionalWayArr:  0.0001092233005464077
isPrimeSquarerootWayArr:  0.0001272089005112648
primeArr (suggested):  0.00006196610003709793
isPrimeSquarerootWayTwoArr:  0.000105714200142771

Iteration 8:

isPrimeConventionalWayArr:  0.00010890220178663731
isPrimeSquarerootWayArr:  0.00012892659988626836
primeArr (suggested):  0.000055275400444865224
isPrimeSquarerootWayTwoArr:  0.00010486920177191496

Iteration 9:

isPrimeConventionalWayArr:  0.00011153739924356342
isPrimeSquarerootWayArr:  0.00012576029987260699
primeArr (suggested):  0.00005680049995332956
isPrimeSquarerootWayTwoArr:  0.00010467480102181434

Iteration 10:

isPrimeConventionalWayArr:  0.00011035799815505743
isPrimeSquarerootWayArr:  0.0001265768006257713
primeArr (suggested):  0.00005575320014730096
isPrimeSquarerootWayTwoArr:  0.00010596680009737611

Sample 10 Million (10000000) Iterations

Iteration 1:

isPrimeConventionalWayArr:  0.00011928780986890197
isPrimeSquarerootWayArr:  0.00012412049009799956
primeArr (suggested):  0.00005793778010234237
isPrimeSquarerootWayTwoArr:  0.00010363322006165981

Iteration 2:

isPrimeConventionalWayArr:  0.00010635640006065368
isPrimeSquarerootWayArr:  0.00012505082993544638
primeArr (suggested):  0.000053171040023490784
isPrimeSquarerootWayTwoArr:  0.00010545557955764234

Iteration 3:

isPrimeConventionalWayArr:  0.00010894328009858727
isPrimeSquarerootWayArr:  0.00012658657005652784
primeArr (suggested):  0.00005493023999705911
isPrimeSquarerootWayTwoArr:  0.00010782274951003491

JSFiddle Link as example:

https://jsfiddle.net/ganeshsurfs/y683v5s2/ Results I used to get for 10 Million iterations are as below:

Iteration 1:

"isPrimeConventionalWayArr: ", 0.0002012
"isPrimeSquarerootWayArr: ", 0.0002838
"primeArr (suggested): ", 0.0002132
"isPrimeSquarerootWayTwoArr: ", 0.0002189

Iteration 2:

"isPrimeConventionalWayArr: ", 0.0002242
"isPrimeSquarerootWayArr: ", 0.0002486
"primeArr (suggested): ", 0.000181
"isPrimeSquarerootWayTwoArr: ", 0.0002145

I barely understand people's code, so here is mine (idk if they are not too clean but i think it's very easy to understand)

    function primeNum (x){


//Array created for final checking
const primeArray =[];
    

//Use for loop for filtering all possibility numbers that have 0 modulo


for (var i = 1 ; i <= x ; i++){
if (x % i === 0){
primeArray.push(i)
}
}
    



//Check the primeArray use if statement


if (primeArray.length === 2){
return "it's a prime boys"
} else {
return "it's not a prime sorry to say"
}
}

the concept is simple, prime number is a number that only can divied by only 2 numbers and has modulo equal to 0 (x % i === 0). So if the primeArray has length more than 2 (more than 2 numbers), it's not a prime number.

i don't know what people says about my code, i need your advice guys. Best Regards.

One line solution Using ternary '?' operator

const primeNum = (num = 1) => num < 2 ? 'Not a prime number' : (num === 2 || num % 2 !== 0) ? 'Prime number' : 'Not a prime number'


console.log(primeNum())
console.log(primeNum(0))
console.log(primeNum(2))
console.log(primeNum(3))