libri-javascript-python

In this lesson we develop a prime number algorithm in JavaScript.

First of all, remember that a number is prime when it has two divisors, namely 1 and itself.

The sequence of prime numbers begins with 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, …

prime number JavaScript – algorithm

Check if a number taken as input is prime.

To check if a number is prime, you need to use a divisor which is incremented by 1 from time to time.

So, I begin to divide the number taken as input, first by 1, then by 2, then by 3, etc.

Clearly in order to do this I have to use a loop, increasing the divisor by 1, after each iteration.

So if, for example, the number were 3 then I would first divide it by 1, then by 2 and then by 3. At the same time I can count the divisors using a special variable, for example named count.

If at the end we find 2 divisors, that is 1 and the number itself, the value of the variable count will be 2 and then the number is prime. Otherwise the number is not prime.

But we can do better. We can consider that the divisor can stop at half of the number itself as it is taken for granted that dividing a number by a value greater than its half you get a decimal number. So we can only count one divisor to define that a number is prime (if count wille be 1 the number is prime).

So here is a possible solution to the algorithm on prime number created in JavaScript:


var n = prompt('Insert a number: ');
while (n < 0){
   n = prompt('Insert a positive number: ');
}
	
var div = 1;
var count = 0;
	
while(count <= 1 && div <= n/2) {
   if(n % div == 0)  {
	count++;	
   }
   div++;
}
	
if (count == 1){
   document.write('The number is prime!');
 }   
 else {
    document.write('The number isn't prime!');
 }

In this algorithm we first checked that the user enters a positive number with a while loop, in the same way we could also use the do while.

The while condition we entered stops as soon as the variable count equals 1 and the divisor has reached half the number.

Conclusion

Clearly this is just a possible solution to the prime number algorithm in JavaScript, please submit yours and let's discuss it in the comments below.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts