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
Contact Us