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
Smallest prime number just greater than the specified number in JavaScript
We are required to write a JavaScript function that takes in a positive integer as the first and the only argument.
The function should find one such smallest prime number which is just greater than the number specified as argument.
For example −
If the input is −
const num = 18;
Then the output should be:
const output = 19;
Understanding Prime Numbers
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. To check if a number is prime, we only need to test divisibility up to its square root.
Algorithm
The approach is straightforward:
- Start checking from the next number after the given input
- For each number, check if it's prime by testing divisibility from 2 to ?number
- Return the first prime number found
Example
Following is the code:
const num = 18;
const justGreaterPrime = (num) => {
for (let i = num + 1;; i++) {
let isPrime = true;
for (let d = 2; d * d <= i; d++) {
if (i % d === 0) {
isPrime = false;
break;
};
};
if (isPrime) {
return i;
};
};
};
console.log(justGreaterPrime(num));
Output
Following is the console output −
19
Testing with Multiple Values
const justGreaterPrime = (num) => {
for (let i = num + 1;; i++) {
let isPrime = true;
for (let d = 2; d * d <= i; d++) {
if (i % d === 0) {
isPrime = false;
break;
};
};
if (isPrime) {
return i;
};
};
};
// Test with different values
console.log("Next prime after 10:", justGreaterPrime(10));
console.log("Next prime after 25:", justGreaterPrime(25));
console.log("Next prime after 50:", justGreaterPrime(50));
console.log("Next prime after 100:", justGreaterPrime(100));
Next prime after 10: 11 Next prime after 25: 29 Next prime after 50: 53 Next prime after 100: 101
How It Works
The function uses a nested loop structure:
- The outer loop iterates through numbers starting from
num + 1 - The inner loop checks if the current number is prime by testing divisibility
- We only check divisors up to ?i because if i has a divisor greater than ?i, it must also have a corresponding divisor less than ?i
- Once a prime is found, the function immediately returns it
Conclusion
This algorithm efficiently finds the next prime number by using trial division up to the square root. The function guarantees to find the smallest prime greater than any given positive integer.
