Last active
August 22, 2017 14:16
-
-
Save JanGorman/c96239dea1b32d061d3b to your computer and use it in GitHub Desktop.
Prime factors Kata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
func primeFactors(of int: Int) -> [Int] { | |
var n = int | |
var factors: [Int] = [] | |
var divisor = 2 | |
while n > 1 { | |
while n % divisor == 0 { | |
factors.append(divisor) | |
n /= divisor | |
} | |
divisor += 1 | |
} | |
return factors | |
} | |
func assertEquals(_ input: [Int], _ expected: [Int]) -> (Bool, String?) { | |
let result = input == expected | |
var message: String? | |
if !result { | |
message = "Expected \(expected), got \(input) instead" | |
} | |
return (result, message) | |
} | |
assertEquals(primeFactors(of: 1), []) | |
assertEquals(primeFactors(of: 2), [2]) | |
assertEquals(primeFactors(of: 3), [3]) | |
assertEquals(primeFactors(of: 4), [2, 2]) | |
assertEquals(primeFactors(of: 5), [5]) | |
assertEquals(primeFactors(of: 6), [2, 3]) | |
assertEquals(primeFactors(of: 7), [7]) | |
assertEquals(primeFactors(of: 8), [2, 2, 2]) | |
assertEquals(primeFactors(of: 9), [3, 3]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment