JavaScript: Check if a Number is Prime

1. Introduction

Prime numbers, the numbers greater than 1 that have no divisors other than 1 and themselves, are a fundamental concept in mathematics. They have crucial implications in various fields, especially in cryptography. In programming, verifying the primality of a number is a standard challenge. Today, we'll create a JavaScript program that checks if a given number is prime or not.

2. Program Overview

During this guide, we'll:

1. Define a number to be tested.

2. Implement a function that will find the prime number.

3. Display the outcome – whether the number is prime or not.

3. Code Program

let num = 19;   // Number to be checked
let isPrime = true;  // Variable to keep track of the number's prime

// Function to check if a number is prime or not
function checkPrime(n) {
    if (n <= 1) {
        return false;  // Numbers less than or equal to 1 are not prime
    }
    for (let i = 2; i <= Math.sqrt(n); i++) {
        if (n % i === 0) {
            return false;  // If n is divisible by any number between 2 and sqrt(n), it's not prime
        }
    }
    return true;
}

isPrime = checkPrime(num);

console.log(num + " is " + (isPrime ? "a prime number." : "not a prime number."));

Output:

19 is a prime number.

4. Step By Step Explanation

1. Variable Declaration: We begin by defining num, which is the number we want to test. We also initialize isPrime as true; this variable will store the final result post-evaluation.

2. Function for Primality Test: The function checkPrime(n) is created to test the primality. For optimization, we only check for factors up to the square root of n because a larger factor of n must be a multiple of a smaller factor that has been already checked.

3. Condition Checks:

- Numbers less than or equal to 1 are inherently non-prime.

- The loop checks if n is divisible by any number from 2 up to the square root of n. If a divisor is found, n is non-prime.

4. Result Assignment: After the function evaluation, the isPrime variable is updated based on the function's return value.

5. Output: Finally, a ternary operator in the console.log function serves to display if the number is prime or not in a clear, comprehensive statement.

Comments