Last active
November 14, 2016 12:32
-
-
Save acegreen/6284f40ae4cc9fbdd74781dbc05921af to your computer and use it in GitHub Desktop.
Playing around with primes
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
// Mark: - Prime fun | |
// isPrime function | |
func isPrime(n: Int) -> Bool { | |
guard n > 1 else { return false } | |
for i in stride(from: n-1, to: 1, by: -1) { | |
if n % i == 0 { | |
return false | |
} | |
} | |
return true | |
} | |
print("isPrime", isPrime(n: 17)) | |
func nextPrime(from n: Int) -> Int { | |
var nextPrime = n + 1 | |
while !isPrime(n: nextPrime) { | |
nextPrime += 1 | |
} | |
return nextPrime | |
} | |
print("next prime", nextPrime(from: 17)) | |
// Prime factors for a number | |
func primeFactorization(n: Int) -> [Int] { | |
var remaining = n | |
var currentPrime = 2 | |
var result = [Int]() | |
while remaining > 1 { | |
while (remaining % currentPrime == 0) { | |
result.append(currentPrime) | |
remaining /= currentPrime | |
} | |
currentPrime = nextPrime(from: currentPrime) | |
} | |
return result | |
} | |
print("prime factors", primeFactorization(n: 20)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment