Algorithms

From Coder Merlin
Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Put simply, an algorithm is a set of instructions to perform a computation. For example, to determine if a number is prime or composite, finding the factors of a number, generating passwords using a given set of characters, etc.

Functions Crash Course[edit]

We'll talk more about functions later on, but for now just know that a function in computer science works similarly to functions in math: the function takes input, does something with it, and returns something. These are useful when writing algorithms because they allow us to write an algorithm once in a program and use it as many times as needed. Here's an example function that returns the given number multiplied by two:

func multiplyByTwo(n: Int) -> Int {
    // 'n' is now defined as the argument passed to the function
    return n * 2
}

let x = multiplyByTwo(n: 8) // x is 16

Put simply, a function in Swift is defined by the keyword func, followed by the function's name, list of parameters, then its return type and lastly the actual code the function will run.

For the following exercises, the function boilerplate will be provided.

Exercises[edit]

Since most of the characters are reserved by Swift, the characters '[?]' will be used to show a fill in the blank.

Parity[edit]

The parity of an integer is whether it is even or odd. In math class, you have most likely already learned that a number is even if it is divisible by two and odd otherwise.

For this exercise, you will complete an algorithm to determine if a number is even. To do this, you can begin by using the below function as a starting point, and replacing the blank with the correct arithmetic operator. The comparison operator == checks for equality between the terms on both sides. So, you'll need an operator that returns the integer 0 if the number is evenly divisible by 2, or any other number otherwise.

func isEven(n: Int) -> Bool {
    return n [?] 2 == 0
}

Looking Ahead[edit]

As an extra exercise, create an isOdd function by looking at some of the non-arithmetic Operators and utilize the already existing isEven function.

func isOdd(n: Int) -> Bool {
    return [?]isEven(n: n)
}

Hint: [?] should be replaced with a single operator