Write JavaScript code to find the smallest prime larger than an input
- User
Write JavaScript code to find the smallest prime larger than an input
- Assistant
Here's a JavaScript solution to find the smallest prime number larger than a given input number:
// Function to check if a number is prime function isPrime(num) { // Numbers less than 2 are not prime if (num < 2) return false; // Check for divisibility up to the square root of num for (let i = 2; i <= Math.sqrt(num); i++) { if (num % i === 0) { return false; } } return true; } // Function to find the smallest prime larger than n function nextPrime(n) { // Start checking from the next number let nextNum = n + 1; // Keep checking numbers until we find a prime while (true) { if (isPrime(nextNum)) { return nextNum; } nextNum++; } } // Test the function function testNextPrime() { // Test cases const testCases = [10, 20, 1, 100, 97]; testCases.forEach(test => { console.log(`Smallest prime larger than ${test} is ${nextPrime(test)}`); }); } // Run the tests testNextPrime(); // Example usage: console.log(nextPrime(10)); // Output: 11 console.log(nextPrime(20)); // Output: 23 console.log(nextPrime(1)); // Output: 2 console.log(nextPrime(100)); // Output: 101 console.log(nextPrime(97)); // Output: 101This code includes:
-
isPrime(num)function:- Checks if a number is prime
- Returns false for numbers less than 2
- Tests divisibility up to the square root of the number (optimization)
- Returns true if no divisors are found
-
nextPrime(n)function:- Takes an input number n
- Starts checking numbers from n + 1
- Returns the first prime number it finds
-
testNextPrime()function:- Includes test cases to demonstrate the functionality
- Logs results to the console
Key features of this implementation:
- Efficient prime checking using square root optimization
- Handles edge cases (numbers less than 2)
- Simple and readable code structure
- Includes test cases for verification
Example outputs:
Smallest prime larger than 10 is 11 Smallest prime larger than 20 is 23 Smallest prime larger than 1 is 2 Smallest prime larger than 100 is 101 Smallest prime larger than 97 is 101To use this code, you can simply call
nextPrime(n)with your desired input number. For example:const result = nextPrime(50); console.log(result); // Output: 53Note that this implementation is suitable for relatively small numbers. For very large numbers, you might want to consider more sophisticated prime-finding algorithms or optimizations, such as the Sieve of Eratosthenes for generating multiple primes or using probabilistic primality tests like Miller-Rabin for very large numbers.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.