Signup/Sign In

JavaScript program to check whether a Number is Prime Number

A prime number is a natural number that is greater than 1 and cannot be made up of two smaller natural numbers. Prime numbers are important in math, and they can be used in many ways in computer science and other fields.

In this program, we will make a JavaScript program that can tell if a given number is a prime number or not. The program will take a number you type in and use a series of steps and calculations to figure out if it is a prime number or not. We'll use different parts of the JavaScript programming language, like loops and if/else statements, to make a program that works well, is correct, and is easy to understand.

What is a Prime Number?

A prime number is a positive integer that is only divisible by 1 and itself.

  • Numbers greater than 1 are tested using a for loop
  • 1 is considered neither prime nor a composite number
  • Prime Numbers can only be on the positive

For example, 2, 3, 5, 7, and 11 are the first few prime numbers.

Approach:

The for loop is used to iterate through the positive numbers to check if the number entered by the user is divisible by positive numbers. Now, we need to implement the condition to check if the number is divisible or not than 1 and itself.

  • The flag variable is used to store a boolean value: either true or false.
  • The flag variable is set to false if the number is not a prime number.
  • The flag variable remains true if the number is a prime number.

program to check Prime number

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

const num = parseInt(prompt("Enter a positive number: "));
let flag = true;


if (num === 1) 
    console.log("1 is neither prime nor composite number.");

// check if num is greater than 1
else if (num > 1) {
    
    for (let i = 2; i < num; i++) {
        if (number % i == 0) {
            flag = false;
            break;
        }
    }
     if (flag) 
        console.log(`${num} is a prime number`);
     else 
        console.log(`${num} is a not prime number`);
}
else 
    console.log("The number entered by the user is not a prime number.");


Enter a positive number: 29
29 is a prime number.

Conclusion

In the end, the JavaScript program that was made to check if a given number is a prime number has proven to be a quick and effective way to determine whether a number is a prime number. The program uses a loop to check if the number entered is divisible by any of the numbers from 2 to the square root of the number entered. If it is, the number you put in is not prime, so the program tells you "Not a prime." If the number you type in can't be divided by any of the numbers in the range, it is a prime number, and the program will return "Prime."



About the author:
Proficient in the creation of websites. Expertise in Java script and C#. Discussing the latest developments in these areas and providing tutorials on how to use them.