find the nth prime number in swift

To find the nth prime number in swift, we can use the following algorithm:

  1. Create an empty array to store the prime numbers found so far.
  2. Initialize a variable i to 2, as 2 is the first prime number.
  3. Loop through the natural numbers (i to infinity).
  4. For each number, loop through the prime numbers found so far.
  5. Check if the current number is divisible by any of the prime numbers found so far. If it is, exit the loop with 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.
  6. If the number of prime numbers found so far is equal to n, return the last prime number in the array.

Here's the Swift code implementing the above algorithm:

main.swift
func nthPrime(_ n: Int) -> Int {
    var primes: [Int] = []
    var i = 2
    while primes.count < n {
        var isPrime = true
        for prime in primes {
            if i % prime == 0 {
                isPrime = false
                break
            }
        }
        if isPrime {
            primes.append(i)
        }
        i += 1
    }
    return primes.last!
}
377 chars
19 lines

Here's an example of how to use the nthPrime function:

main.swift
let primeNumber = nthPrime(10) // returns 29
45 chars
2 lines

gistlibby LogSnag