2018-10-12 15:37:13 -04:00
|
|
|
---
|
2019-07-30 00:25:58 +05:30
|
|
|
title: 'Problem 7: 10001st prime'
|
2018-10-12 15:37:13 -04:00
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Problem 7: 10001st prime
|
|
|
|
|
|
|
|
---
|
|
|
|
## Problem Explanation
|
2018-10-12 15:37:13 -04:00
|
|
|
- A prime number is a number which is divided by 1 and itself.
|
|
|
|
- We can find a number is prime if it's not divisible by other prime numbers smaller than itself.
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
```js
|
|
|
|
function nthPrime(n) {
|
|
|
|
//Primes array which will store all the prime numbers
|
|
|
|
const primes = [2];
|
2019-07-24 00:59:27 -07:00
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
//Num is the number we want to check
|
2019-07-24 00:59:27 -07:00
|
|
|
let num = 3,
|
|
|
|
isPrime = true;
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
//Looping until primes array is equal to n
|
2019-07-24 00:59:27 -07:00
|
|
|
while (primes.length < n) {
|
2018-11-07 15:34:13 +00:00
|
|
|
//All the primes numbers of a number is always <= its square root
|
2018-10-12 15:37:13 -04:00
|
|
|
let max = Math.ceil(Math.sqrt(num));
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
for (let i = 0; primes[i] <= max; i++) {
|
2018-10-12 15:37:13 -04:00
|
|
|
if (num % primes[i] == 0) {
|
|
|
|
//Looping till we find the prime
|
|
|
|
isPrime = false;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
2019-07-24 00:59:27 -07:00
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
//if Prime found, push it to the array
|
|
|
|
if (isPrime) primes.push(num);
|
|
|
|
isPrime = true;
|
2019-07-24 00:59:27 -07:00
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
//An optimization technique, since we know of all even numbers only 2 is a prime number, we can skip the rest
|
2019-07-24 00:59:27 -07:00
|
|
|
num += 2;
|
2018-10-12 15:37:13 -04:00
|
|
|
}
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
//Returning the last number
|
|
|
|
return primes[primes.length - 1];
|
2018-10-12 15:37:13 -04:00
|
|
|
}
|
|
|
|
```
|
2019-07-01 06:49:24 -07:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
#### Relevant Links
|
2018-10-12 15:37:13 -04:00
|
|
|
- [Wikipedia](https://en.wikipedia.org/wiki/Prime_number)
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
</details>
|