check if a number is prime in swift

To check if a number is prime in Swift, we can use a simple for-loop that iterates from 2 to the square root of the number we want to check.

main.swift
func isPrime(number: Int) -> Bool {
    if number < 2 {
        return false
    }
    for i in 2...Int(sqrt(Double(number))) {
        if number % i == 0 {
            return false
        }
    }
    return true
}
216 chars
12 lines

In this code, we first check if the number is less than 2, because 0 and 1 are not prime numbers. Then, we iterate from 2 to the square root of the number using the sqrt function from the Foundation framework. We use the modulo operator % to check if the number is divisible by any of the integers in the iteration. If it is, it means the number is not prime and we return false. Otherwise, we return true.

To optimize this function, we can iterate only up to the integer part of the square root of the number (sqrt(number) instead of sqrt(Double(number))). We can also add a special case for 2, since it's the only even prime number. Here's the optimized function:

main.swift
func isPrime(number: Int) -> Bool {
    if number < 2 {
        return false
    }
    if number == 2 {
        return true
    }
    if number % 2 == 0 {
        return false
    }
    for i in 3...Int(sqrt(number)) {
        if number % i == 0 {
            return false
        }
    }
    return true
}
307 chars
18 lines

gistlibby LogSnag