Check Prime Number using for Loop
The basic method to check for a prime number is by using a loop to divide the number by each integer less than its square root.
Javascript
function isPrime(number) { if (number <= 1) { return false ; } for (let i = 2; i <= Math.sqrt(number); i++) { if (number % i === 0) { return false ; } } return true ; } // Driver code 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