[Solved] Check if a number is prime in JavaScript

  

3
Topic starter

Write a JS function to check if a number is prime (only wholly divisible by itself and one). The input comes as a single number argument.

Examples:

Input: 81

Output: false


Input: 7

Output: true


Input: 8

Output: false


The output should be the return value of your function. Return true for prime number and false otherwise.

1 Answer
2

Here is my Javascript script:

function isPrime(input) {
    let prime = true;
    for (let i = 2; i <= Math.sqrt(input); i++) {
        if (input % i == 0) {
            prime = false;
            break;
        }
    }
    return prime && (input > 1);
}
 
console.log(isPrime(8));
Share: