By reducing iterations in the loop
We can optimize our code by directly terminating iterations for some numbers like 1, 2, and 3. By doing this, we can start iteration from 5 and go till sqrt(num). We will increment the iterator value with 6 everytime, because the prime numbers can be expressed as 6n+1 or 6n-1.
Example: The below code will explain the above approach with its practical implementation.
function checkPrime(num) {
// Conditions to reduce iterations
if (num <= 1)
return false;
if (num == 2 || num == 3)
return true;
if (num % 2 == 0 || num % 3 == 0)
return false;
// Incrementing iterator with 6 to reduce iterations
for (let i = 5; i * i <= num; i = i + 6)
if (num % i == 0 || num % (i + 2) == 0)
return false;
return true;
}
checkPrime(4) ? console.log("Passed number is prime") :
console.log("Passed number is not prime");
checkPrime(5) ? console.log("Passed number is prime") :
console.log("Passed number is not prime");
Output
Passed number is not prime Passed number is 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