1 min read

Check whether given number is prime or not - JavaScript

Check whether given number is prime or not - JavaScript

Today we are going to attend a question.

Write a JavaScript program to check whether number given is a prime number or not. If the number is prime then print number to the document along with the text “it is a prime number”.

First of all, what is a prime number?

A natural number greater than one has not any other divisors except 1 and itself. In other word we can say which has only two divisors, 1 and the number itself. For example, 5 is a prime number and cannot be divided by 1 or itself.

Answer

let number = 17;
let i = 2;

for(i; i<=number; i++){
  if(number % i == 0) break;
}

if( number == i ) document.write("it is a prime number");
else document.write("it is not a prime number");

Answer Explained

In the For Loop, we are using an If Statement to check if the number has no remainder.

The code “number % i” is used to find the remainder to check whether the remainder is 0 or 1. So that we can see if the “i” is equal to the “number” or not. If the remainder of the “number” is zero and the “i” is equal to the “number“, then the number is considered to be a prime number.

Algorithm

I understand the explanation is kind of confusing. So, here is an Algorithm for that.

Step 1: Start
Step 2: Initialize variables number=17, i=2
Step 3: Repeat the steps until i less than or equal to number
             3.2 if remainder of number is equal to 0, go to Step 4
             3.2 increment i by 1
Step 4: if number is equal to i
             Display "It is a prime number"
        Else
             Display "It is not a prime number"
Goto 5: Stop

That’s it

Read More

JavaScript For Loop

If JavaScript

Also subscribe to my YouTube channel to get more lessons every week inshaAllah.