Algorithm


  1. Input: Accept a positive integer as input.
  2. Edge Cases: Check if the input is less than 2. If yes, it's not a prime number.
  3. Loop: Iterate from 2 to the square root of the input number (rounded up to the nearest integer).
    • If the input number is divisible evenly by any number in this range, it's not a prime number.
  4. Output: If the loop completes without finding a divisor, the number is a prime number.

 

Code Examples

#1 Code Example- Check Prime Number

Code - Javascript Programming

// program to check if a number is prime or not

// take input from the user
const number = parseInt(prompt("Enter a positive number: "));
let isPrime = true;

// check if number is equal to 1
if (number === 1) {
    console.log("1 is neither prime nor composite number.");
}

// check if number is greater than 1
else if (number > 1) {

    // looping through 2 to number-1
    for (let i = 2; i  <  number; i++) {
        if (number % i == 0) {
            isPrime = false;
            break;
        }
    }

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

// check if number is less than 1
else {
    console.log("The number is not a prime number.");
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter a positive number: 23
23 is a prime number.
Advertisements

Demonstration


JavaScript Programing Example to Check Prime Number-DevsEnv

Previous
JavaScript Practice Example #3 - Assign 3 Variables and Print Good Way