Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A Swift implementation of the Collatz Conjecture, with full playground markup.
import UIKit
//: # The Collatz Conjecture
//: *This process will eventually reach the number 1, regardless of which positive integer is chosen initially. (See [Wikipedia](*
//: \
//: Create an array to capture the sequence of numbers returned by the `collatz` function.
var sequence = [Int]()
//: The `collatz(start:Int, initial:Bool) -> [Int]` function takes an integer and will perform the following:
//:- if the integer (`n`) is 1, it will return an `[Int]` array.
//:- if the integer (`n`) is even, it will divide `n` by 2, append `n` to `[Int]`, and run the function again with `n`.
//:- if the integer (`n`) is odd, it will perform multiply `n` by 3 and add 1, add `n` to `[Int]`, and run the function again with `n`.
//: - note: If `initial` == `true`, the `start` variable is added to `[Int]`.
func collatz(start:Int, initial:Bool = true) -> [Int] {
var n = start
if initial == true {
if n == 1 {
return sequence
else if n % 2 == 0 {
n /= 2
else {
n = (3 * n) + 1
return collatz(start: n, initial: false)
- example: The basic use case for the `collatz` function.\
The array in this example contains all values for the sequence starting at n = 27. var x = n is used to show the graph.
for n in collatz(start: 27, initial: true) {
var x = n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment