Created
June 3, 2014 21:41
-
-
Save SlaunchaMan/b5823b7d4e9cb2e56281 to your computer and use it in GitHub Desktop.
A quick Prime Factors kata in Swift
This file contains hidden or 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
import XCTest | |
func primeFactors(n: Int) -> Int[] { | |
if n == 1 { | |
return [1] | |
} | |
var result: Int[] = [] | |
var number = n | |
var divisor = 2 | |
func testDivisor(divisor: Int) { | |
while number > divisor && number % divisor == 0 { | |
result.append(divisor); | |
number /= divisor | |
} | |
} | |
testDivisor(2) | |
for var i = 3; Double(i) <= sqrt(Double(n)); i += 2 { | |
testDivisor(i) | |
} | |
if number > 1 { | |
result.append(number) | |
} | |
return result | |
} | |
class SwiftPrimeFactorsTests: XCTestCase { | |
func testOne() { | |
XCTAssert(primeFactors(1) == [1], "The prime factor of 1 is 1") | |
} | |
func testTwo() { | |
XCTAssert(primeFactors(2) == [2], "The prime factor of 2 is 2") | |
} | |
func testThree() { | |
let expected: Int[] = [3] | |
XCTAssert(primeFactors(3) == [3], "The prime factor of 3 is 3") | |
} | |
func testFour() { | |
XCTAssert(primeFactors(4) == [2, 2], "The prime factors of 4 are [2, 2]") | |
} | |
func testFive() { | |
XCTAssert(primeFactors(5) == [5], "The prime factor of 5 is 5") | |
} | |
func testSix() { | |
XCTAssert(primeFactors(6) == [2, 3], "The prime factors of 6 are [2, 3]") | |
} | |
func testSeven() { | |
XCTAssert(primeFactors(7) == [7], "The prime factor of 7 is [7]") | |
} | |
func testEight() { | |
XCTAssert(primeFactors(8) == [2, 2, 2], "The prime factors of 2 are [2, 2, 2]") | |
} | |
func testNine() { | |
XCTAssert(primeFactors(9) == [3, 3], "The prime factors of 9 are [3, 3]") | |
} | |
func testLargeNumber() { | |
XCTAssert(primeFactors(1155) == [3, 5, 7, 11], "The prime factors of 1155 are [3, 5, 7, 11]") | |
} | |
func testAbsurdNumber() { | |
let candidate = 2 * 2 * 3 * 3 * 5 * 5 * 7 * 11 * 13 | |
XCTAssert(primeFactors(candidate) == [2, 2, 3, 3, 5, 5, 7, 11, 13], "The prime factors of \(candidate) are [2, 2, 3, 3, 5, 5, 7, 11, 13]") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment