Skip to content

Instantly share code, notes, and snippets.

@nuclearace
Last active October 30, 2019 11:54
Show Gist options
  • Select an option

  • Save nuclearace/b2c087e114d4b792cd54cb675e15219c to your computer and use it in GitHub Desktop.

Select an option

Save nuclearace/b2c087e114d4b792cd54cb675e15219c to your computer and use it in GitHub Desktop.
import Foundation
import Playground
private let lock = DispatchSemaphore(value: 1)
private let queue = DispatchQueue(label: "worker", attributes: .concurrent)
private let nWorkers = 5
private let stopAt = 1 << 30
private var i = 33550336
private var running = nWorkers
func calculatePerfect() {
queue.async {
lock.wait()
let n = i
i += 1
guard n < stopAt else {
running -= 1
if running == 0 {
exit(0)
}
lock.signal()
return
}
lock.signal()
if n.isMultiple(of: 100_000) {
print("Passing \(n)")
}
if n.isPerfectNumber {
print("\(n) is perfect")
}
calculatePerfect()
}
}
for _ in 0..<nWorkers {
calculatePerfect()
}
dispatchMain()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment