To find the nth prime number, we need to loop through numbers till we get the nth prime number. We can write a function that checks if a number is a prime number and then push all prime numbers into an array. Once we reach the nth prime number, we return that number.
Here's the code:
index.tsx389 chars24 lines
First, we define a function isPrime
that checks if a number is a prime number. We loop through all numbers from 2 to the square root of num
and check if any number divides num
without a remainder. If yes, we know it's not a prime number and return false
. If we have gone through all the numbers and found no divisor, we know it is a prime number and return true
.
Next, we define a function nthPrime
that finds and returns the nth prime number. We create an empty array primes
to store all prime numbers we find. We loop through all numbers starting from 2 until we have found n
prime numbers. For each number, we call the isPrime
function to check if it's a prime number. If it is, we push it into the primes
array. Once we have found n
prime numbers, we return the last element (the nth) from the primes
array.
gistlibby LogSnag