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.

40,026 questions

51,982 answers

573 users

How to check if a number is prime in Swift

1 Answer

0 votes
import Foundation

func isPrime(_ num: Int) -> Bool {
    if num == 0 || num == 1 {
        return false
    }
    
    for p in 2...Int(sqrt(Double(num))) {
        if num % p == 0 {
            return false
        }
    }
    
    return true
}

for _ in 1...20 {
    let n = Int.random(in: 1...200)
    if isPrime(n) {
        print("\(n) - Prime")
    } else {
        print("\(n) - NOT Prime")
    }
}



/*
run:
 
160 - NOT Prime
88 - NOT Prime
163 - Prime
49 - NOT Prime
92 - NOT Prime
129 - NOT Prime
101 - Prime
96 - NOT Prime
79 - Prime
112 - NOT Prime
104 - NOT Prime
178 - NOT Prime
90 - NOT Prime
103 - Prime
160 - NOT Prime
69 - NOT Prime
175 - NOT Prime
178 - NOT Prime
23 - Prime
26 - NOT Prime

*/

 



answered Oct 29, 2024 by avibootz
...