斯威夫特:灵异筛

这将是一个很小的出版物,我受到本文的启发 不,我不会与那里提出的解决方案竞争(为了简洁起见),但是作为Swift功能的证明,对于habrasociety来说很有趣。

该解决方案完全重复了Wikipedia中描述的算法,无需进行任何修改。

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)))) . ") 

那些感兴趣的人可以在此沙箱中试用。 我设法压缩的最大值-在8,500,000左右的范围内,搜索大约需要6秒钟。 不幸的是,在我的Mac Mini 2014后期(Core i5,8 GB)上,已经在参数max = 1,000,000的操场上运行此代码会导致刹车,所以要小心。 在上面的链接上,一切旋转得更快。

Source: https://habr.com/ru/post/zh-CN450888/


All Articles