
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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 Articles
- Finding the nth palindrome number amongst whole numbers in JavaScript
- Finding the nth missing number from an array 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 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 digit of natural numbers JavaScript
- JavaScript: Finding nearest prime number greater or equal to sum of digits - JavaScript
- Finding the nth power of array element present at nth index using JavaScript
- Finding the nth day from today - JavaScript (JS Date)
- Finding nth element of the Padovan sequence using JavaScript
- Finding nth digit of natural numbers sequence in JavaScript
- Finding all possible prime pairs that sum upto input number using JavaScript

Advertisements