Write a JavaScript program to check prime number
Description: Check whether the numbers 2, 15, 17 and 1 are prime.
Hint:
- A prime number is greater than 1 and has no divisor other than 1 and itself.
- Test divisors up to the square root.
JavaScript prime number program
function isPrime(n) {
if (n < 2) return false;
for (let i = 2; i <= Math.sqrt(n); i++) {
if (n % i === 0) return false;
}
return true;
}
for (const n of [2, 15, 17, 1]) {
console.log(n + (isPrime(n) ? " is prime" : " is not prime"));
}
Output:
Tutorials Class - Output Window
2 is prime
15 is not prime
17 is prime
1 is not prime
How it works
- Numbers below 2 are not prime.
- For 15 the loop finds that
15 % 3 === 0and returnsfalse. - As soon as one divisor is found, the function returns.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |