JavaScript Program to Check if a Number is Prime

Introduction

A prime number is a number greater than 1 that has no divisors other than 1 and itself. Determining whether a number is prime is a fundamental problem in mathematics and programming. This program will help you check if a given number is prime using JavaScript.

Problem Statement

Create a JavaScript program that:

  • Accepts a number.
  • Checks if the number is prime.
  • Returns true if the number is prime, otherwise false.

Example:

  • Input: 7

  • Output: 7 is a prime number

  • Input: 10

  • Output: 10 is not a prime number

Solution Steps

  1. Read the Input Number: Provide the number either by user input or directly within the code.
  2. Check Prime Conditions: Use a loop to check divisibility from 2 to the square root of the number.
  3. Display the Result: Print whether the number is prime or not.

JavaScript Program

// JavaScript Program to Check if a Number is Prime
// Author: https://www.javaguides.net/

function isPrime(number) {
    // Step 1: Handle special cases for numbers less than 2
    if (number <= 1) {
        return false;
    }

    // Step 2: Check divisibility from 2 to the square root of the number
    for (let i = 2; i <= Math.sqrt(number); i++) {
        if (number % i === 0) {
            return false; // Not a prime number
        }
    }

    // Step 3: If no divisors are found, the number is prime
    return true;
}

// Example input
let inputNumber = 7;
if (isPrime(inputNumber)) {
    console.log(`${inputNumber} is a prime number`);
} else {
    console.log(`${inputNumber} is not a prime number`);

Output

7 is a prime number

Example with Different Input

let inputNumber = 10;
if (isPrime(inputNumber)) {
    console.log(`${inputNumber} is a prime number`);
} else {
    console.log(`${inputNumber} is not a prime number`);

Output:

10 is not a prime number

Explanation

Step 1: Handle Numbers Less Than 2

  • Prime numbers must be greater than 1, so any number less than or equal to 1 is automatically not prime.

Step 2: Check Divisibility

  • The isPrime() function checks divisibility from 2 up to the square root of the number. If any number divides evenly, the function returns false, indicating that the number is not prime.

Step 3: Display the Result

  • If no divisors are found, the function returns true, meaning the number is prime. The result is printed using console.log().

Conclusion

This JavaScript program demonstrates how to check whether a number is prime by checking divisibility. The algorithm efficiently reduces the number of checks by only testing up to the square root of the number, making it faster for larger numbers. This is a simple yet crucial problem-solving technique used in various applications involving prime numbers.

Comments