Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Listing all the prime numbers upto a specific number in JavaScript
We are required to write a JavaScript function that takes in a number, say n, and returns an array containing all the prime numbers up to n.
For example: If the number n is 24.
Then the output should be ?
const output = [2, 3, 5, 7, 11, 13, 17, 19, 23];
Therefore, let's write the code for this function ?
Method 1: Using Helper Function for Prime Check
This approach uses a helper function to check if a number is prime, then iterates through numbers up to n:
const num = 24;
const isPrime = num => {
let count = 2;
while(count {
if(num
[
2, 3, 5, 7, 11,
13, 17, 19, 23
]
Method 2: Optimized Prime Check Using Square Root
This version improves efficiency by only checking divisors up to the square root of the number:
const primeUptoOptimized = num => {
if(num {
if(n
[
2, 3, 5, 7, 11,
13, 17, 19, 23, 29
]
How It Works
The first method checks each number by testing divisibility from 2 to half the number. The second method uses mathematical optimization:
- Numbers divisible by 2 or 3 (except 2 and 3 themselves) are not prime
- All primes greater than 3 can be written as 6k ± 1
- Only check divisors up to ?n since larger factors would have corresponding smaller factors
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| Helper Function | O(n²/2) | Small numbers, learning |
| Square Root Check | O(n?n) | Larger numbers, efficiency |
Conclusion
Both methods successfully find all prime numbers up to a given limit. The optimized version using square root checking is more efficient for larger numbers and follows mathematical principles for prime detection.
