

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding nearest prime to a specified number in 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.
Therefore, let’s write the code for this function −
Example
The code for this will be −
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));
Output
The output in the console will be −
29
- Related Questions & Answers
- Nearest Prime to a number - JavaScript
- JavaScript: Finding nearest prime number greater or equal to sum of digits - JavaScript
- Finding nearest Gapful number in JavaScript
- Summing up digits and finding nearest prime in JavaScript
- Finding next prime number to a given number using JavaScript
- Finding the nth prime number in JavaScript
- Finding points nearest to origin in JavaScript
- Finding the largest prime factor of a number in JavaScript
- Smallest prime number just greater than the specified number in JavaScript
- Print the nearest prime number formed by adding prime numbers to N
- Finding two prime numbers with a specific number gap in JavaScript
- Nearest prime less than given number n C++
- Nearest power 2 of a number - JavaScript
- Finding all possible prime pairs that sum upto input number using JavaScript
- Is the reversed number a prime number in JavaScript
Advertisements