I just finished Project Euler #10 in Swift, and since there is not any version yet on Code Review, I would like to have some comments on what I did to try to improve it.
I hope I learned some from the previous code reviews :).
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
import Foundation
func summationOfPrimesBelow(var n:Int) -> Int {
assert(n > 0, "argument must be positive")
var composite = [Bool](count: n, repeatedValue: false)
var x = 2
let maxPrime = Int(ceil(sqrt(Double(n))))
while x <= maxPrime {
if composite[x] == false {
for y in stride(from: x * x, through: n - 1, by: x) {
composite[y] = true
}
}
x++
}
var result = 0
for i in stride(from: 2, through: composite.count - 1, by: 1) {
if composite[i] == false {
result += i
}
}
return result
}
func euler10() {
let number = summationOfPrimesBelow(2_000_000)
println(number)
}
func printTimeElapsedWhenRunningCode(operation:() -> ()) {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
println("Time elapsed : \(timeElapsed) s")
}
printTimeElapsedWhenRunningCode(euler10)
The code executes in 0.012s in Release mode.