PUBLISHED ON: MARCH 14, 2023
JavaScript Program to Print All Prime Numbers in an Interval
Prime numbers are an essential concept in mathematics and computer science, with applications ranging from cryptography to algorithm design. A prime number is a integer that is positive and larger than 1 that has only two positive divisors, 1 and itself. In other words, it is a number that cannot be evenly divided by any other positive whole number except for 1 and itself.
This tutorial will teach us how to write a program in JavaScript to print all the Prime Numbers in between a range. We also have an interactive JavaScript course where you can learn JavaScript from basics to advanced and get certified. Check out the course and learn more from here.
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 user is prompted to enter two limits the lower point and the upper point. Then the Prime Number between those two points is listed. 2 loops are used in the given code.
The first loop runs from the Lower Bound to the Upper Bound as destined by the user.
The second loop runs basically for the Primality test for the ith value of the Bound in the first Loop.
- A variable flag is set to 0.
- Inside the second loop, the value of i is divided by each number from 2 to a value one less than i (i - 1).
- Finally, all the numbers that have a flag 0 (not divisible by other numbers) are printed.
Code:
// JavaScript Program to print prime numbers between the two numbers
var lowerr = parseInt(prompt('Enter lower number: '));
var higher = parseInt(prompt('Enter higher number: '));
console.log(`The prime numbers between ${lower} and ${higher} are given below:`);
// looping from lower to higher
for (let i = lower; i <= higher; i++) {
var flag = 0;
// looping through 2 to ith for the primality test
for (let j = 2; j < i; j++) {
if (i % j == 0) {
flag = 1;
break;
}
}
if (flag == 0 && i!=1) {
console.log(i);
}
}
Enter lower number: 2
Enter higher number : 13
The prime numbers between 2 and 13 are:
2
3
5
7
11
13
Conclusion
In conclusion, the JavaScript program to print all prime numbers in an interval is a useful tool for anyone who needs to find prime numbers within a given range. This program utilises a simple algorithm to identify and print all prime numbers within the specified interval. By understanding the logic behind the program, developers can modify it to suit their specific needs, such as finding prime numbers within larger or smaller intervals. Overall, this JavaScript program offers a practical and efficient solution for identifying prime numbers and can be a valuable addition to any developer's toolkit.