Forgotten Player agucova Forgotten Player agucova - 11 months ago 167
Swift Question

Check if a number is prime? (Pseudocode)

I'm trying to make an app on Xcode (Swift) that checks whether a number is prime or not.
Can someone help me with some pseudocode to check the number?
I need a simple answer, not incredibly advanced algorithms. I'm new to programming.


A simple method is to check all factors up to the square-root of the number. This is NOT the most efficient method, but is sufficient for most numbers you will likely be inputting in an iPhone app. (see for more complex algorithms).

function is_prime(n: int)
    if n <= 1
        return false

    if n <= 3
        return true

    i = 2
    while i*i <= n
        if n % i == 0
           return false
        i = i + 1
    return true