Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,923 questions

51,856 answers

573 users

How to calculate the Nth prime number in Swift

1 Answer

0 votes
// 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73

import Foundation

func isPrime(_ num: Int) -> Bool {
    if num <= 1 { return false }
    if num <= 3 { return true }
    if num % 2 == 0 || num % 3 == 0 { return false }
    var i = 5
    while i * i <= num {
        if num % i == 0 || num % (i + 2) == 0 { return false }
        i += 6
    }
    return true
}

func getTheNthPrimeNumber(_ n: Int) -> Int {
    var count = 0
    var num = 1
    while count < n {
        num += 1
        if isPrime(num) {
            count += 1
        }
    }
    return num
}

let n = 9

print("The \(n)th prime number is \(getTheNthPrimeNumber(n))")



/*
run:  
 
The 9th prime number is 23
 
*/

 



answered Dec 12, 2024 by avibootz
...