Check Prime Number using Recursion

Recursion can also be used to check for prime numbers. We will create a method which will call itself again and again to check whether the passed number is prime or not.

Javascript




function isPrime(number, divisor = 2) {
    if (number <= 1) {
        return false;
    } else if (divisor > Math.sqrt(number)) {
        return true;
    } else if (number % divisor === 0) {
        return false;
    } else {
        return isPrime(number, divisor + 1);
    }
}
  
console.log(isPrime(5));
console.log(isPrime(4));
console.log(isPrime(11));
console.log(isPrime(21));


Output

true
false
true
false


JavaScript Program to Check Prime Number By Creating a Function

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In this article, we will explore how to check if a given number is a prime number in JavaScript by creating a function.

Table of Content

  • Check Prime Number using for Loop
  • Check Prime Number using Array Methods
  • Check Prime Number using Recursion

Similar Reads

Check Prime Number using for Loop

The basic method to check for a prime number is by using a loop to divide the number by each integer less than its square root....

Check Prime Number using Array Methods

...

Check Prime Number using Recursion

We can also use JavaScript array methods to create a more functional approach. In this approach, we create an array of potential divisors using Array.from and then use the every method to check that none of them divides the number evenly....

Contact Us