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.swift216 chars12 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.swift307 chars18 lines
gistlibby LogSnag