![]() |
In this article, we will explore a JavaScript program to find and print all prime numbers within a given range. A prime number is a natural number greater than 1, which is only divisible by 1 and itself. The first few prime numbers are 2 3 5 7 11 13 17 19 23…, The program efficiently identifies and displays prime numbers within the specified range. ![]() prime numbers There are several methods that can be used to Print All Prime Numbers in an Interval.
We will explore all the above methods along with their basic implementation with the help of examples. Approach 1: Using the Trial Division Method in JavaScriptIn this approach, we will check divisibility for each number in the interval. In the below program, the range of numbers is taken as input and stored in the variables ‘a’ and ‘b’. Then using a for-loop, the numbers between the interval of a and b are traversed. Example: Javascript
Output
2 3 5 7 11 Time Complexity: O(N2), Where N is the difference between the range Approach 3: Using Optimised SolutionIn this approach, we will use the fact that even numbers (except 2) cannot be prime can significantly optimize the process of finding prime numbers within a specified interval. Example: Javascript
Output
5 7 11 13 17 19 23 Time Complexity: O(N*sqrt(N)), Where N is the difference between the range Approach 2: Using the Optimized Sieve of Eratosthenes AlgorithmThe Sieve of Eratosthenes is an efficient algorithm to find all prime numbers up to a given number by eliminating multiples of each prime iteratively. Example: In this example we are using the optimized Sieve of Eratosthenes algorithm to find and print prime numbers within the user-provided interval, efficiently identifying primes and displaying them. Javascript
Output
Prime numbers between 10 and 20 (Sieve of Eratosthenes - Optimized): 11 13 17 19 |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 9 |