How to use the root value of given number In Javascript
We can use square root value of the given number to check if it is prime. Because, if we represent a number as product of two numbers as n=a*b, then any one of a and b will be smaller than square root of n. If the number is divisible by any one of them, then it will be a prime number.
Example: This example shows the implementation of the above-explained appraoch.
function checkPrime(num){
let res = true;
if(num<=1){
res = false;
}
for(let i=2; i*i<=num; i++){
if(num%i===0){
res = false;
break;
}
}
if(res){
console.log(num, " is a prime number.");
}
else{
console.log(num, " is not a prime number.");
}
}
checkPrime(4);
checkPrime(5);
Output
4 is not a prime number. 5 is a prime number.
Time Complexity: O(sqrt(n))
Auxiliary Space: O(1)
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