Skip to content

Instantly share code, notes, and snippets.

@topher6345
Created June 10, 2015 01:14
Show Gist options
  • Save topher6345/fbbe51b751563cd54688 to your computer and use it in GitHub Desktop.
Save topher6345/fbbe51b751563cd54688 to your computer and use it in GitHub Desktop.
Seive of Eratosthenes
import Cocoa
enum Status {
case unmarked, prime, composite
}
class SeiveOfEratosthenes {
let ceiling: Int
let ceiling_sqrt: Int
var table = [Int: Status]()
var results = [Int]()
init(ceiling: Int){
self.ceiling = ceiling
self.ceiling_sqrt = Int(sqrt(Double(ceiling)))
// Initialize table as all numbers unmarked
for index in 2...(self.ceiling) {
self.table[index] = Status.unmarked
}
}
func mark_table() {
for index in 2...ceiling_sqrt {
if table[index] != Status.unmarked{
continue
}
self.table[index] = Status.prime
var multiples_of_index = index
while (multiples_of_index < ceiling) {
multiples_of_index = multiples_of_index + index
table[multiples_of_index] = Status.composite
}
}
for (key, value) in table {
if value != Status.composite {
results.append(key)
}
}
}
func get_table() -> Dictionary<Int,Status> {
return self.table
}
func get_results () -> [Int] {
return sorted(self.results)
}
}
var seive = SeiveOfEratosthenes(ceiling: 100)
seive.mark_table()
println(seive.get_results())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment