determine if a number is prime in swift

Here's a simple function in Swift to determine if a number is prime:

main.swift
func isPrime(number: Int) -> Bool {
    if number <= 1 {
        return false
    }
    
    if number <= 3 {
        return true
    }
    
    var i = 2
    while i * i <= number {
        if number % i == 0 {
            return false
        }
        i += 1
    }
    
    return true
}
291 chars
20 lines

The function starts by checking if the number is less than or equal to 1. If so, it immediately returns false, since 1 and lower numbers are not prime. If the number is less than or equal to 3, it returns true, since 2 and 3 are prime.

The function then uses a while loop to check if the number is divisible by any integer from 2 up to the square root of the number. If it is, the function immediately returns false, since a prime number should only be divisible by 1 and itself.

If the function hasn't returned false after the loop, it returns true, since the number must be prime.

gistlibby LogSnag