How to use recursive approach In Javascript
We will create a method which will call itself again and again to check whether the passed number is prime or not.
Example: The below code implements the recursive method to check if the number is prime or not.
function checkPrime(num, div = 2) {
if (num <= 1) {
return false;
}
if (div > Math.sqrt(num)) {
return true;
}
if (num % div === 0) {
return false;
}
else {
return checkPrime(num, div + 1);
}
}
console.log(checkPrime(5) ? "Passed number is Prime" :
"Passed number is not Prime");
console.log(checkPrime(4) ? "Passed number is Prime" :
"Passed number is not Prime");
Output
Passed number is Prime Passed number is not Prime
Check a number is Prime or not using JavaScript
We are given a positive integer N and the task is to find out whether the given number is prime or not. A prime number is a number that is divisible by 1 and itself only.
Examples:
Input: N = 4 Output: Not Prime Explanation: The given number 4 is also dividble by 2 other than 1 and itself. Input: 5 Output: Prime Explanation: 5 can only be divisible by 1 and itself.
These are the following ways to solve this problem:
Table of Content
- Checking prime number using Flag variable
- Using the root value of given number
- Using recursive approach
- By reducing iterations in the loop
- Using Regular Expression
Contact Us