A friend of mine was administering a whiteboard test to a prospective hire. He asked what he thought was a straightforward question. Can you write a function to solve for prime? The young lion fumbled around and offered that he thought there was a pre-defined one function from .Net. He never produced a working function and was never hired.

This made me think about how well I might do in the same situation. I think I would do a fair bit of fumbling so I decided to write my own function ahead of time… write it down on a piece of paper… then quickly tear it up so no one would know….

I encourage you to think this over between cute dog videos on youtube and come up with your own answer. Here is the definition from Google in case you need a refresher.

A **prime number** is a **whole number** greater than 1, whose only two **whole-number factors** are 1 and itself. The first few **prime numbers** are 2, 3, 5, 7, 11, 13, 17, 19, 23, and 29. As we proceed in the set of **natural numbers** N = {1, 2, 3, …}, the primes become less and less frequent in general.

I decided to out myself here and show my work. Maybe you will face this age old question some day but here is what I came up with.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
func isPrime(num: Int)-> Bool{ switch num { case 0,1: return false default: for index in 2..<num { if num % index == 0 { return false } } return true } } // just to test it on a range on Int's var primeArray = [Int]() for index in 1...30 { if isPrime(num: index) { primeArray.append(index) } } print(primeArray) |