Simple numerical testing in JavaScript

I am trying to end a codewars call that asks you to check if a number is a prime number. For some reason, my solution doesn't seem to work for a square of odd primes (e.g. 9 returns true instead of false).

function isPrime(num) {

  if (num === 2) {
    return true;
  }
  else if(num > 1){
    for (var i = 2;  i < num; i++) {

      if (num % i !== 0 ) {
        return true;
      }

      else if (num === i * i) {
        return false
      }

      else {
        return false;
      }
    }
  }
  else {
    return false;
  }

}

console.log(isPrime(121));

Ps I included this second else / if statement because I was trying to solve the problem.

+15
source share
26 answers

As simple as possible:

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

With ES6 syntax:

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

You can also reduce the complexity of the algorithm from O(n)to O(sqrt(n))if you run a loop until you get the square root of:

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

A small suggestion here, why do you want to start a loop for integer n numbers?

, 2 (1 ). , 1, , , , .

. :

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;
}

O (sqrt (n))

, , ?

,

+22

:

const isPrime = n => ![...Array(n).keys()].slice(2).map(i => !(n%i)).includes(true) && ![0,1].includes(n)
+9
function isPrime(num) {
  if (num <= 1) return false; // negatives
  if (num % 2 == 0 && num > 2) return false; // even numbers
  let s = Math.sqrt(num); // store the square to loop faster
  for(let i = 3; i <= s; i++) { // start from 3, stop at the square, increment
      if(num % i === 0) return false; // modulo shows a divisor was found
  }
  return true;
}
+6

// 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);
Hide result
+5

6f ± 1, 2 3, f -

 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;
 }

: O (sqrt (n))

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

DEMO

+3
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 not a prime number so return false
  }
  return n > 1; // otherwise it 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
+3

, :

// 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 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');
}
Hide result

- ( 11/2018) TC , , , , ( ).

+3

javascript - . .

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)

+1

, :

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
Hide result
+1

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');
   }
Hide result
+1

. .

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 a prime no.
}
return true;
}

, . . . .

, , . . - 15,35.. . .

0

if "if" for. num = 9 = 2, 9% i! == 0, 9 , , = 3, 9% === 0.

.

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;
};

if . for 2 n - , , .

, !

0

:

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))
0

:

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));
0

:

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;
}
0

const isPrime = num => {
  for (var i = 2; i < num; i++) if (num % i == 0) return false;
  return num >= 2; 
}
0
(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));
0
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';
   }
 }

isAPrimeNumber(), .

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

:

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

, ,

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

Ticked

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;
}

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
}

isPrime (1) false

isPrime (100) false

isPrime (-100) false

6 ? 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)

isPrime (7) true//Prime 4

isPrime (8) false

isPrime (9)

isPrime (10) false

isPrime (11) true//Prime 5

isPrime (12)

isPrime (13) true//Prime 6

0

. , , . , 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;
}
Hide result
0

function isPrime(n){
	if (isNaN(n) || !isFinite(n) || n%1 || 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;
}
Hide result

0

. ( 3 )

   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;        
   }
-1
source

The following code uses the most efficient looping method 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 2 and lower numbers and all even numbers
  2. Using Math.sqrt () to minimize the number of loops
  3. Increase the cycle counter by 2, skip all even numbers, further halve the number of cycles
-1
source

Source: https://habr.com/ru/post/1658584/


All Articles