📜 ⬆️ ⬇️

Swift: Eratosthenes Sieve

It will be a very small publication that was inspired by this article. No, I'm not going to compete with the solution proposed there (except in short), but maybe, as a demonstration of Swift's capabilities, it will be interesting for the habrasoobschestvu.

The solution absolutely repeats the algorithm described in Wikipedia , without any modifications.

import Foundation //   extension Int { func powerOf2() -> Int { return self * self } } //   ? let max = 8_500_000 //    var testValue = 2 let startTime = Date() //   var data = (2...max).map{$0} let allocationTime = Date() //  while (testValue.powerOf2() <= max) { data.removeAll(where: {$0 >= testValue.powerOf2() && $0.isMultiple(of: testValue)}) testValue = data.first(where: {$0 > testValue})! } let overallTime = Date() //   print(" \(data.count)  : ", data) print() print(" : \(String(format: "%.2f",(allocationTime.timeIntervalSince(startTime)))) . ") print(": \(String(format: "%.2f",(overallTime.timeIntervalSince(allocationTime)))) . ") print(": \(String(format: "%.2f",(overallTime.timeIntervalSince(startTime)))) . ") 

Anyone can play with it in this sandbox. The maximum that I managed to squeeze there - in the region of 8,500,000, the search takes about 6 seconds. Unfortunately, running this code in the playground on my Mac Mini Late 2014 (Core i5, 8 GB) already with the parameter max = 1 000 000 leads to wild brakes, so be careful. On the link given above everything turns much quicker.

')

Source: https://habr.com/ru/post/450888/


All Articles