Checking prime number using Flag variable
In this approach, we create a function and use for loop with a flag varibale which will be set to false if the number is not prime and show the result on the user screen based on the value of flag variable.
Example: This example shows the implementation of the above-explained approach.
// Function to check prime number
function checkPrime(num) {
let i, flag = true;
for (i = 2; i <= num - 1; i++) {
if (num % i == 0) {
flag = false;
break;
}
}
if (flag == true)
console.log(num + " is prime");
else
console.log(num + " is not prime");
}
checkPrime(4);
checkPrime(5);
Output
4 is not prime 5 is prime
Time Complexity: O(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