To find the nth prime number in swift, we can use the following algorithm:
i
to 2, as 2 is the first prime number.i
to infinity).break
because it cannot be a prime number. If the loop completes without finding any divisors, add the number to the list of prime numbers found so far.n
, return the last prime number in the array.Here's the Swift code implementing the above algorithm:
main.swift377 chars19 lines
Here's an example of how to use the nthPrime
function:
main.swift45 chars2 lines
gistlibby LogSnag