- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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 next prime number to a given number using JavaScript
Problem
We are required to write a JavaScript function that takes in a number n. Our function should that smallest number which is just greater than n and is a prime number.
Example
Following is the code −
const num = 101; const isPrime = (num) => { let sqrtnum = Math.floor(Math.sqrt(num)); let prime = num !== 1; for(let i = 2; i < sqrtnum + 1; i++){ if(num % i === 0){ prime = false; break; }; }; return prime; } const nextPrime = (num = 1) => { while(!isPrime(++num)){ }; return num; }; console.log(nextPrime(num));
Output
103
Advertisements
To Continue Learning Please Login
Login with Google