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
Nearest Prime to a number - JavaScript
We are required to write a JavaScript function that takes in a number and returns the first prime number that appears after n.
For example: If the number is 24, then the output should be 29.
Understanding Prime Numbers
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. Examples include 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, etc.
Implementation
We'll create two functions: one to check if a number is prime, and another to find the nearest prime after a given number.
const num = 24;
const isPrime = n => {
if (n === 1) {
return false;
} else if (n === 2) {
return true;
} else {
for (let x = 2; x < n; x++) {
if (n % x === 0) {
return false;
}
}
return true;
}
};
const nearestPrime = num => {
while (!isPrime(++num)) {};
return num;
};
console.log(nearestPrime(24));
29
How It Works
The isPrime function checks if a number is prime by:
- Returning
falsefor 1 (not considered prime) - Returning
truefor 2 (the only even prime) - Testing divisibility from 2 to n-1 for other numbers
The nearestPrime function increments the input number until it finds a prime using the isPrime helper function.
Optimized Version
For better performance, we can optimize the prime checking by only testing up to the square root of n:
const isPrimeOptimized = n => {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 === 0 || n % 3 === 0) return false;
for (let i = 5; i * i <= n; i += 6) {
if (n % i === 0 || n % (i + 2) === 0) {
return false;
}
}
return true;
};
const nearestPrimeOptimized = num => {
while (!isPrimeOptimized(++num)) {};
return num;
};
// Test with different numbers
console.log(nearestPrimeOptimized(24)); // 29
console.log(nearestPrimeOptimized(50)); // 53
console.log(nearestPrimeOptimized(100)); // 101
29 53 101
Conclusion
Finding the nearest prime involves incrementing from the given number and testing each candidate for primality. The optimized version significantly improves performance for larger numbers by reducing the number of divisibility tests needed.
