settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Check if a number is prime in JavaScript

+4 votes

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.

asked in JavaScript category by user icabe
recategorized by user golearnweb

1 Answer

+4 votes

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));

 

answered by user richard8502
...