Skip to content

Instantly share code, notes, and snippets.

@acegreen
Last active November 14, 2016 12:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acegreen/6284f40ae4cc9fbdd74781dbc05921af to your computer and use it in GitHub Desktop.
Save acegreen/6284f40ae4cc9fbdd74781dbc05921af to your computer and use it in GitHub Desktop.
Playing around with primes
// 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