
- 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 the nth prime number in JavaScript
We are required to write a JavaScript function that takes in a number as the only argument, let's call the number n. The function should find and return the nth prime number from the starting.
For example −
if n = 6, then the output should be: 13
Example
Following is the code −
const findPrime = num => { let i, primes = [2, 3], n = 5; const isPrime = n => { let i = 1, p = primes[i], limit = Math.ceil(Math.sqrt(n)); while (p <= limit) { if (n % p === 0) { return false; } i += 1; p = primes[i]; } return true; } for (i = 2; i <= num; i += 1) { while (!isPrime(n)) { n += 2; } primes.push(n); n += 2; }; return primes[num - 1]; } console.log(findPrime(6)); console.log(findPrime(16)); console.log(findPrime(66));
Output
Following is the output on console −
13 53 317
- Related Questions & Answers
- Finding the nth missing number from an array JavaScript
- Finding the nth palindrome number amongst whole numbers in JavaScript
- Finding the nth element of the lucas number sequence in JavaScript
- Finding the largest prime factor of a number in JavaScript
- Finding nearest prime to a specified number in JavaScript
- Finding next prime number to a given number using JavaScript
- Finding the nth digit of natural numbers JavaScript
- Finding a number and its nth multiple in an array in JavaScript
- Finding two prime numbers with a specific number gap in JavaScript
- Finding the nth day from today - JavaScript (JS Date)
- Finding nth element of the Padovan sequence using JavaScript
- Finding the nth power of array element present at nth index using JavaScript
- JavaScript: Finding nearest prime number greater or equal to sum of digits - JavaScript
- Finding the power of prime number p in n! in C++
- Finding all possible prime pairs that sum upto input number using JavaScript
Advertisements