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,845 questions

51,766 answers

573 users

How to find the first 4-digit prime number where all digits are unique in Swift

1 Answer

0 votes
import Foundation

func isPrime(_ n: Int) -> Bool {
    if n < 2 { return false }
    if n % 2 == 0 { return n == 2 }

    let limit = Int(sqrt(Double(n)))
    var i = 3
    while i <= limit {
        if n % i == 0 { return false }
        i += 2
    }
    
    return true
}

func hasUniqueDigits(_ n: Int) -> Bool {
    let digits = String(n)
    
    return Set(digits).count == digits.count
}

func main() {
    for num in 1000...9999 {
        if isPrime(num) && hasUniqueDigits(num) {
            print("First 4-digit prime with all unique digits: \(num)")
            return
        }
    }
    print("No such number found.")
}

main()



/*
run:

First 4-digit prime with all unique digits: 1039

*/

 



answered Nov 21, 2025 by avibootz
...