From 216ce997f469e3512810be962d9c437979e2936b Mon Sep 17 00:00:00 2001 From: Pratikbhai Patel Date: Thu, 9 Jun 2016 13:28:01 -0400 Subject: [PATCH 01/10] Add prime generation --- Prime Numbers/PrimeSieve.swift | 29 ++++++++++++ Prime Numbers/README.md | 39 ++++++++++++++++ .../SievePrimes.playground/Contents.swift | 44 +++++++++++++++++++ .../contents.xcplayground | 4 ++ .../contents.xcworkspacedata | 7 +++ 5 files changed, 123 insertions(+) create mode 100644 Prime Numbers/PrimeSieve.swift create mode 100644 Prime Numbers/README.md create mode 100644 Prime Numbers/SievePrimes.playground/Contents.swift create mode 100644 Prime Numbers/SievePrimes.playground/contents.xcplayground create mode 100644 Prime Numbers/SievePrimes.playground/playground.xcworkspace/contents.xcworkspacedata diff --git a/Prime Numbers/PrimeSieve.swift b/Prime Numbers/PrimeSieve.swift new file mode 100644 index 000000000..6859a8d88 --- /dev/null +++ b/Prime Numbers/PrimeSieve.swift @@ -0,0 +1,29 @@ +infix operator ^^ { associativity left precedence 160 } +func ^^ (radix: Int, power: Int) -> Int { + return Int(pow(CGFloat(radix), CGFloat(power))) +} + +infix operator .. {associativity left precedence 60 } + +func ..(left: T, right: T.Stride) -> (T, T.Stride) { + return (left, right) +} + +func ..(left: (T, T.Stride), right: T) -> [T] { + return [T](left.0.stride(through: right, by: left.1)) +} + + +func primesTo(max: Int) -> [Int] { + let m = Int(sqrt(ceil(Double(max)))) + let set = NSMutableSet(array: 3..2..max) + set.addObject(2) + for i in (2..1..m) { + if (set.containsObject(i)) { + for j in i^^2..i..max { + set.removeObject(j) + } + } + } + return set.sortedArrayUsingDescriptors([NSSortDescriptor(key: "integerValue", ascending: true)]) as! [Int] +} \ No newline at end of file diff --git a/Prime Numbers/README.md b/Prime Numbers/README.md new file mode 100644 index 000000000..2c3aa0081 --- /dev/null +++ b/Prime Numbers/README.md @@ -0,0 +1,39 @@ +# Sieve Primes + +Goal: To quickly get an array of prime numbers with a specified limit using the Sieve of Eratosthenes. + +The Sieve of Eratosthenes is an algorithm that finds all primes numbers up to any given limit. + +Here's an implementation in Swift that should be easy to understand: + +``` +func primesTo(max: Int) -> [Int] { + let m = Int(sqrt(ceil(Double(max)))) + let set = NSMutableSet(array: 3..2..max) + set.addObject(2) + for i in (2..1..m) { + if (set.containsObject(i)) { + for j in i^^2..i..max { + set.removeObject(j) + } + } + } + return set.sortedArrayUsingDescriptors([NSSortDescriptor(key: "integerValue", ascending: true)]) as! [Int] +} +``` + +Put this code in a playground and test it like so: + +``` +let primesArray = primesTo(50) +print(primesArray) +// prints [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] +``` + +--*write some introduction to the Sieve of Eratosthenes*-- + +## See also + +[Sieve of Eratosthenes on Wikipedia](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) + +*Written for Swift Algorithm Club by Pratikbhai Patel* \ No newline at end of file diff --git a/Prime Numbers/SievePrimes.playground/Contents.swift b/Prime Numbers/SievePrimes.playground/Contents.swift new file mode 100644 index 000000000..21e500b79 --- /dev/null +++ b/Prime Numbers/SievePrimes.playground/Contents.swift @@ -0,0 +1,44 @@ +//: Playground - noun: a place where people can play + +import Foundation +import UIKit + +infix operator ^^ { associativity left precedence 160 } +func ^^ (radix: Int, power: Int) -> Int { + return Int(pow(CGFloat(radix), CGFloat(power))) +} + +infix operator .. {associativity left precedence 60 } + +func ..(left: T, right: T.Stride) -> (T, T.Stride) { + return (left, right) +} + +func ..(left: (T, T.Stride), right: T) -> [T] { + return [T](left.0.stride(through: right, by: left.1)) +} + +func primesTo(max: Int) -> [Int] { + assert(max > 1, "Prime numbers can only be above 1") + print("Getting all primes under \(max)") + let m = Int(sqrt(ceil(Double(max)))) + print("Need to remove all multiples of numbers through \(m)") + let set = NSMutableSet(array: 3..2..max) + set.addObject(2) + print(set) + for i in (2..1..m) { + if (set.containsObject(i)) { + print("Removing all multiples of \(i)") + for j in i^^2..i..max { + print("removing j: \(j)") + set.removeObject(j) + } + } + } + return set.sortedArrayUsingDescriptors([NSSortDescriptor(key: "integerValue", ascending: true)]) as! [Int] +} + +let startDate = NSDate().timeIntervalSince1970 * 1000 +print(primesTo(50)) +let endDate = NSDate().timeIntervalSince1970 * 1000 +print("Prime generation time: \(endDate - startDate) ms.") \ No newline at end of file diff --git a/Prime Numbers/SievePrimes.playground/contents.xcplayground b/Prime Numbers/SievePrimes.playground/contents.xcplayground new file mode 100644 index 000000000..5da2641c9 --- /dev/null +++ b/Prime Numbers/SievePrimes.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/Prime Numbers/SievePrimes.playground/playground.xcworkspace/contents.xcworkspacedata b/Prime Numbers/SievePrimes.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..919434a62 --- /dev/null +++ b/Prime Numbers/SievePrimes.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + From fbba3db3ac1edacdf90e177e8a96cfda2981a886 Mon Sep 17 00:00:00 2001 From: Pratikbhai Patel Date: Mon, 13 Jun 2016 10:18:07 -0400 Subject: [PATCH 02/10] =?UTF-8?q?Add=20Atkins=E2=80=99=20sieve=20Rename=20?= =?UTF-8?q?files=20Add=20project?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Prime Numbers/Atkins_Sieve.swift | 54 ++ ...meSieve.swift => Eratosthenes_Sieve.swift} | 0 .../Primes/Primes.xcodeproj/project.pbxproj | 507 ++++++++++++++++++ .../contents.xcworkspacedata | 7 + Prime Numbers/Primes/Primes/AppDelegate.swift | 135 +++++ .../AppIcon.appiconset/Contents.json | 68 +++ .../Primes/Base.lproj/LaunchScreen.storyboard | 27 + .../Primes/Primes/Base.lproj/Main.storyboard | 25 + Prime Numbers/Primes/Primes/Info.plist | 47 ++ .../Primes/Primes/ViewController.swift | 25 + Prime Numbers/Primes/PrimesTests/Info.plist | 24 + .../Primes/PrimesTests/PrimesTests.swift | 36 ++ Prime Numbers/Primes/PrimesUITests/Info.plist | 24 + .../Primes/PrimesUITests/PrimesUITests.swift | 36 ++ .../SievePrimes.playground/Contents.swift | 52 +- 15 files changed, 1063 insertions(+), 4 deletions(-) create mode 100644 Prime Numbers/Atkins_Sieve.swift rename Prime Numbers/{PrimeSieve.swift => Eratosthenes_Sieve.swift} (100%) create mode 100644 Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj create mode 100644 Prime Numbers/Primes/Primes.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 Prime Numbers/Primes/Primes/AppDelegate.swift create mode 100644 Prime Numbers/Primes/Primes/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 Prime Numbers/Primes/Primes/Base.lproj/LaunchScreen.storyboard create mode 100644 Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard create mode 100644 Prime Numbers/Primes/Primes/Info.plist create mode 100644 Prime Numbers/Primes/Primes/ViewController.swift create mode 100644 Prime Numbers/Primes/PrimesTests/Info.plist create mode 100644 Prime Numbers/Primes/PrimesTests/PrimesTests.swift create mode 100644 Prime Numbers/Primes/PrimesUITests/Info.plist create mode 100644 Prime Numbers/Primes/PrimesUITests/PrimesUITests.swift diff --git a/Prime Numbers/Atkins_Sieve.swift b/Prime Numbers/Atkins_Sieve.swift new file mode 100644 index 000000000..3d733545d --- /dev/null +++ b/Prime Numbers/Atkins_Sieve.swift @@ -0,0 +1,54 @@ +infix operator ^^ { associativity left precedence 160 } +func ^^ (radix: Int, power: Int) -> Int { + return Int(pow(CGFloat(radix), CGFloat(power))) +} + +infix operator .. {associativity left precedence 60 } + +func ..(left: T, right: T.Stride) -> (T, T.Stride) { + return (left, right) +} + +func ..(left: (T, T.Stride), right: T) -> [T] { + return [T](left.0.stride(through: right, by: left.1)) +} + + +func primesTo(max: Int) -> [Int] { + var is_prime = [Bool](count: max + 1, repeatedValue: false) + is_prime[2] = true + is_prime[3] = true + let limit = Int(ceil(sqrt(Double(max)))) + for x in 1...limit { + for y in 1...limit { + var num = 4 * x * x + y * y + if (num <= max && (num % 12 == 1 || num % 12 == 5)) { + is_prime[num] = true + } + num = 3 * x * x + y * y + if (num <= max && num % 12 == 7) { + is_prime[num] = true + } + if (x > y) { + num = 3 * x * x - y * y + if (num <= max && num % 12 == 11) { + is_prime[num] = true + } + } + } + } + if limit > 5 { + for i in 5...limit { + if is_prime[i] { + for j in (i * i)..i..max { + is_prime[j] = false + } + } + } + } + var primesArray = [Int]() + for (idx, val) in is_prime.enumerate() { + if val == true { primesArray.append(idx) } + } + return primesArray +} \ No newline at end of file diff --git a/Prime Numbers/PrimeSieve.swift b/Prime Numbers/Eratosthenes_Sieve.swift similarity index 100% rename from Prime Numbers/PrimeSieve.swift rename to Prime Numbers/Eratosthenes_Sieve.swift diff --git a/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj b/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj new file mode 100644 index 000000000..2f4958a28 --- /dev/null +++ b/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj @@ -0,0 +1,507 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 46; + objects = { + +/* Begin PBXBuildFile section */ + 31900F441D0EF73700F8673F /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31900F431D0EF73700F8673F /* AppDelegate.swift */; }; + 31900F461D0EF73700F8673F /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31900F451D0EF73700F8673F /* ViewController.swift */; }; + 31900F491D0EF73700F8673F /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 31900F471D0EF73700F8673F /* Main.storyboard */; }; + 31900F4B1D0EF73700F8673F /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 31900F4A1D0EF73700F8673F /* Assets.xcassets */; }; + 31900F4E1D0EF73700F8673F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 31900F4C1D0EF73700F8673F /* LaunchScreen.storyboard */; }; + 31900F591D0EF73700F8673F /* PrimesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31900F581D0EF73700F8673F /* PrimesTests.swift */; }; + 31900F641D0EF73700F8673F /* PrimesUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31900F631D0EF73700F8673F /* PrimesUITests.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 31900F551D0EF73700F8673F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 31900F381D0EF73700F8673F /* Project object */; + proxyType = 1; + remoteGlobalIDString = 31900F3F1D0EF73700F8673F; + remoteInfo = Primes; + }; + 31900F601D0EF73700F8673F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 31900F381D0EF73700F8673F /* Project object */; + proxyType = 1; + remoteGlobalIDString = 31900F3F1D0EF73700F8673F; + remoteInfo = Primes; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXFileReference section */ + 31900F401D0EF73700F8673F /* Primes.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Primes.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 31900F431D0EF73700F8673F /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 31900F451D0EF73700F8673F /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + 31900F481D0EF73700F8673F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 31900F4A1D0EF73700F8673F /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 31900F4D1D0EF73700F8673F /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 31900F4F1D0EF73700F8673F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 31900F541D0EF73700F8673F /* PrimesTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PrimesTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 31900F581D0EF73700F8673F /* PrimesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimesTests.swift; sourceTree = ""; }; + 31900F5A1D0EF73700F8673F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 31900F5F1D0EF73700F8673F /* PrimesUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PrimesUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 31900F631D0EF73700F8673F /* PrimesUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimesUITests.swift; sourceTree = ""; }; + 31900F651D0EF73700F8673F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 31900F3D1D0EF73700F8673F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 31900F511D0EF73700F8673F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 31900F5C1D0EF73700F8673F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 31900F371D0EF73700F8673F = { + isa = PBXGroup; + children = ( + 31900F421D0EF73700F8673F /* Primes */, + 31900F571D0EF73700F8673F /* PrimesTests */, + 31900F621D0EF73700F8673F /* PrimesUITests */, + 31900F411D0EF73700F8673F /* Products */, + ); + sourceTree = ""; + }; + 31900F411D0EF73700F8673F /* Products */ = { + isa = PBXGroup; + children = ( + 31900F401D0EF73700F8673F /* Primes.app */, + 31900F541D0EF73700F8673F /* PrimesTests.xctest */, + 31900F5F1D0EF73700F8673F /* PrimesUITests.xctest */, + ); + name = Products; + sourceTree = ""; + }; + 31900F421D0EF73700F8673F /* Primes */ = { + isa = PBXGroup; + children = ( + 31900F431D0EF73700F8673F /* AppDelegate.swift */, + 31900F451D0EF73700F8673F /* ViewController.swift */, + 31900F471D0EF73700F8673F /* Main.storyboard */, + 31900F4A1D0EF73700F8673F /* Assets.xcassets */, + 31900F4C1D0EF73700F8673F /* LaunchScreen.storyboard */, + 31900F4F1D0EF73700F8673F /* Info.plist */, + ); + path = Primes; + sourceTree = ""; + }; + 31900F571D0EF73700F8673F /* PrimesTests */ = { + isa = PBXGroup; + children = ( + 31900F581D0EF73700F8673F /* PrimesTests.swift */, + 31900F5A1D0EF73700F8673F /* Info.plist */, + ); + path = PrimesTests; + sourceTree = ""; + }; + 31900F621D0EF73700F8673F /* PrimesUITests */ = { + isa = PBXGroup; + children = ( + 31900F631D0EF73700F8673F /* PrimesUITests.swift */, + 31900F651D0EF73700F8673F /* Info.plist */, + ); + path = PrimesUITests; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 31900F3F1D0EF73700F8673F /* Primes */ = { + isa = PBXNativeTarget; + buildConfigurationList = 31900F681D0EF73700F8673F /* Build configuration list for PBXNativeTarget "Primes" */; + buildPhases = ( + 31900F3C1D0EF73700F8673F /* Sources */, + 31900F3D1D0EF73700F8673F /* Frameworks */, + 31900F3E1D0EF73700F8673F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Primes; + productName = Primes; + productReference = 31900F401D0EF73700F8673F /* Primes.app */; + productType = "com.apple.product-type.application"; + }; + 31900F531D0EF73700F8673F /* PrimesTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 31900F6B1D0EF73700F8673F /* Build configuration list for PBXNativeTarget "PrimesTests" */; + buildPhases = ( + 31900F501D0EF73700F8673F /* Sources */, + 31900F511D0EF73700F8673F /* Frameworks */, + 31900F521D0EF73700F8673F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 31900F561D0EF73700F8673F /* PBXTargetDependency */, + ); + name = PrimesTests; + productName = PrimesTests; + productReference = 31900F541D0EF73700F8673F /* PrimesTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + 31900F5E1D0EF73700F8673F /* PrimesUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 31900F6E1D0EF73700F8673F /* Build configuration list for PBXNativeTarget "PrimesUITests" */; + buildPhases = ( + 31900F5B1D0EF73700F8673F /* Sources */, + 31900F5C1D0EF73700F8673F /* Frameworks */, + 31900F5D1D0EF73700F8673F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 31900F611D0EF73700F8673F /* PBXTargetDependency */, + ); + name = PrimesUITests; + productName = PrimesUITests; + productReference = 31900F5F1D0EF73700F8673F /* PrimesUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 31900F381D0EF73700F8673F /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0730; + LastUpgradeCheck = 0730; + ORGANIZATIONNAME = "Pratikbhai Patel"; + TargetAttributes = { + 31900F3F1D0EF73700F8673F = { + CreatedOnToolsVersion = 7.3.1; + }; + 31900F531D0EF73700F8673F = { + CreatedOnToolsVersion = 7.3.1; + TestTargetID = 31900F3F1D0EF73700F8673F; + }; + 31900F5E1D0EF73700F8673F = { + CreatedOnToolsVersion = 7.3.1; + TestTargetID = 31900F3F1D0EF73700F8673F; + }; + }; + }; + buildConfigurationList = 31900F3B1D0EF73700F8673F /* Build configuration list for PBXProject "Primes" */; + compatibilityVersion = "Xcode 3.2"; + developmentRegion = English; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 31900F371D0EF73700F8673F; + productRefGroup = 31900F411D0EF73700F8673F /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 31900F3F1D0EF73700F8673F /* Primes */, + 31900F531D0EF73700F8673F /* PrimesTests */, + 31900F5E1D0EF73700F8673F /* PrimesUITests */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 31900F3E1D0EF73700F8673F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 31900F4E1D0EF73700F8673F /* LaunchScreen.storyboard in Resources */, + 31900F4B1D0EF73700F8673F /* Assets.xcassets in Resources */, + 31900F491D0EF73700F8673F /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 31900F521D0EF73700F8673F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 31900F5D1D0EF73700F8673F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 31900F3C1D0EF73700F8673F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 31900F461D0EF73700F8673F /* ViewController.swift in Sources */, + 31900F441D0EF73700F8673F /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 31900F501D0EF73700F8673F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 31900F591D0EF73700F8673F /* PrimesTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 31900F5B1D0EF73700F8673F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 31900F641D0EF73700F8673F /* PrimesUITests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 31900F561D0EF73700F8673F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 31900F3F1D0EF73700F8673F /* Primes */; + targetProxy = 31900F551D0EF73700F8673F /* PBXContainerItemProxy */; + }; + 31900F611D0EF73700F8673F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 31900F3F1D0EF73700F8673F /* Primes */; + targetProxy = 31900F601D0EF73700F8673F /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 31900F471D0EF73700F8673F /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 31900F481D0EF73700F8673F /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 31900F4C1D0EF73700F8673F /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 31900F4D1D0EF73700F8673F /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 31900F661D0EF73700F8673F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 31900F671D0EF73700F8673F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 9.3; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 31900F691D0EF73700F8673F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = Primes/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.Primes; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 31900F6A1D0EF73700F8673F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + INFOPLIST_FILE = Primes/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.Primes; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; + 31900F6C1D0EF73700F8673F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + INFOPLIST_FILE = PrimesTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.PrimesTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Primes.app/Primes"; + }; + name = Debug; + }; + 31900F6D1D0EF73700F8673F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + INFOPLIST_FILE = PrimesTests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.PrimesTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Primes.app/Primes"; + }; + name = Release; + }; + 31900F6F1D0EF73700F8673F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + INFOPLIST_FILE = PrimesUITests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.PrimesUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_TARGET_NAME = Primes; + }; + name = Debug; + }; + 31900F701D0EF73700F8673F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + INFOPLIST_FILE = PrimesUITests/Info.plist; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.PrimesUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + TEST_TARGET_NAME = Primes; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 31900F3B1D0EF73700F8673F /* Build configuration list for PBXProject "Primes" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 31900F661D0EF73700F8673F /* Debug */, + 31900F671D0EF73700F8673F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 31900F681D0EF73700F8673F /* Build configuration list for PBXNativeTarget "Primes" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 31900F691D0EF73700F8673F /* Debug */, + 31900F6A1D0EF73700F8673F /* Release */, + ); + defaultConfigurationIsVisible = 0; + }; + 31900F6B1D0EF73700F8673F /* Build configuration list for PBXNativeTarget "PrimesTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 31900F6C1D0EF73700F8673F /* Debug */, + 31900F6D1D0EF73700F8673F /* Release */, + ); + defaultConfigurationIsVisible = 0; + }; + 31900F6E1D0EF73700F8673F /* Build configuration list for PBXNativeTarget "PrimesUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 31900F6F1D0EF73700F8673F /* Debug */, + 31900F701D0EF73700F8673F /* Release */, + ); + defaultConfigurationIsVisible = 0; + }; +/* End XCConfigurationList section */ + }; + rootObject = 31900F381D0EF73700F8673F /* Project object */; +} diff --git a/Prime Numbers/Primes/Primes.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/Prime Numbers/Primes/Primes.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 000000000..b317c9b29 --- /dev/null +++ b/Prime Numbers/Primes/Primes.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/Prime Numbers/Primes/Primes/AppDelegate.swift b/Prime Numbers/Primes/Primes/AppDelegate.swift new file mode 100644 index 000000000..6fd2b66de --- /dev/null +++ b/Prime Numbers/Primes/Primes/AppDelegate.swift @@ -0,0 +1,135 @@ +// +// AppDelegate.swift +// Primes +// +// Created by Pratikbhai Patel on 6/13/16. +// Copyright © 2016 Pratikbhai Patel. All rights reserved. +// + +import UIKit + +infix operator ^^ { associativity left precedence 160 } +func ^^ (radix: Int, power: Int) -> Int { + return Int(pow(CGFloat(radix), CGFloat(power))) +} + +infix operator .. {associativity left precedence 60 } + +func ..(left: T, right: T.Stride) -> (T, T.Stride) { + return (left, right) +} + +func ..(left: (T, T.Stride), right: T) -> [T] { + return [T](left.0.stride(through: right, by: left.1)) +} + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + + func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + // Override point for customization after application launch. + performPrimesGeneration() + return true + } + + func applicationWillResignActive(application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(application: UIApplication) { + // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + func performPrimesGeneration() { + + let primesTo = 1_000_000 + + func eratosthenes_sieve(max: Int) -> [Int] { + assert(max > 1, "Prime numbers can only be above 1") + print("Getting all primes under \(max)") + let m = Int(sqrt(ceil(Double(max)))) + let set = NSMutableSet(array: 3..2..max) + set.addObject(2) + for i in (2..1..m) { + if (set.containsObject(i)) { + for j in i^^2..i..max { + set.removeObject(j) + } + } + } + return set.sortedArrayUsingDescriptors([NSSortDescriptor(key: "integerValue", ascending: true)]) as! [Int] + } + + var startDate = NSDate().timeIntervalSince1970 * 1000 + // print(eratosthenes_sieve(5000)) + let era_sieve = eratosthenes_sieve(primesTo) + var endDate = NSDate().timeIntervalSince1970 * 1000 + print("Prime generation time for sieve of eratosthenes: \(endDate - startDate) ms.") + + func atkins_sieve(max: Int) -> [Int] { + var is_prime = [Bool](count: max + 1, repeatedValue: false) + is_prime[2] = true + is_prime[3] = true + let limit = Int(ceil(sqrt(Double(max)))) + for x in 1...limit { + for y in 1...limit { + var num = 4 * x * x + y * y + if (num <= max && (num % 12 == 1 || num % 12 == 5)) { + is_prime[num] = true + } + num = 3 * x * x + y * y + if (num <= max && num % 12 == 7) { + is_prime[num] = true + } + if (x > y) { + num = 3 * x * x - y * y + if (num <= max && num % 12 == 11) { + is_prime[num] = true + } + } + } + } + if limit > 5 { + for i in 5...limit { + if is_prime[i] { + for j in (i * i)..i..max { + is_prime[j] = false + } + } + } + } + var primesArray = [Int]() + for (idx, val) in is_prime.enumerate() { + if val == true { primesArray.append(idx) } + } + return primesArray + } + + startDate = NSDate().timeIntervalSince1970 * 1000 + // print(atkins_sieve(5000)) + let at_sieve = atkins_sieve(primesTo) + endDate = NSDate().timeIntervalSince1970 * 1000 + print("Prime generation time for atkins sieve: \(endDate - startDate) ms.") + print("they are equal \(era_sieve == at_sieve)") + } + + +} + diff --git a/Prime Numbers/Primes/Primes/Assets.xcassets/AppIcon.appiconset/Contents.json b/Prime Numbers/Primes/Primes/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000..36d2c80d8 --- /dev/null +++ b/Prime Numbers/Primes/Primes/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/Prime Numbers/Primes/Primes/Base.lproj/LaunchScreen.storyboard b/Prime Numbers/Primes/Primes/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 000000000..2e721e183 --- /dev/null +++ b/Prime Numbers/Primes/Primes/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard b/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard new file mode 100644 index 000000000..3a2a49bad --- /dev/null +++ b/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Prime Numbers/Primes/Primes/Info.plist b/Prime Numbers/Primes/Primes/Info.plist new file mode 100644 index 000000000..40c6215d9 --- /dev/null +++ b/Prime Numbers/Primes/Primes/Info.plist @@ -0,0 +1,47 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/Prime Numbers/Primes/Primes/ViewController.swift b/Prime Numbers/Primes/Primes/ViewController.swift new file mode 100644 index 000000000..c77924158 --- /dev/null +++ b/Prime Numbers/Primes/Primes/ViewController.swift @@ -0,0 +1,25 @@ +// +// ViewController.swift +// Primes +// +// Created by Pratikbhai Patel on 6/13/16. +// Copyright © 2016 Pratikbhai Patel. All rights reserved. +// + +import UIKit + +class ViewController: UIViewController { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + +} + diff --git a/Prime Numbers/Primes/PrimesTests/Info.plist b/Prime Numbers/Primes/PrimesTests/Info.plist new file mode 100644 index 000000000..ba72822e8 --- /dev/null +++ b/Prime Numbers/Primes/PrimesTests/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/Prime Numbers/Primes/PrimesTests/PrimesTests.swift b/Prime Numbers/Primes/PrimesTests/PrimesTests.swift new file mode 100644 index 000000000..eece41230 --- /dev/null +++ b/Prime Numbers/Primes/PrimesTests/PrimesTests.swift @@ -0,0 +1,36 @@ +// +// PrimesTests.swift +// PrimesTests +// +// Created by Pratikbhai Patel on 6/13/16. +// Copyright © 2016 Pratikbhai Patel. All rights reserved. +// + +import XCTest +@testable import Primes + +class PrimesTests: XCTestCase { + + override func setUp() { + super.setUp() + // Put setup code here. This method is called before the invocation of each test method in the class. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testExample() { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + + func testPerformanceExample() { + // This is an example of a performance test case. + self.measureBlock { + // Put the code you want to measure the time of here. + } + } + +} diff --git a/Prime Numbers/Primes/PrimesUITests/Info.plist b/Prime Numbers/Primes/PrimesUITests/Info.plist new file mode 100644 index 000000000..ba72822e8 --- /dev/null +++ b/Prime Numbers/Primes/PrimesUITests/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/Prime Numbers/Primes/PrimesUITests/PrimesUITests.swift b/Prime Numbers/Primes/PrimesUITests/PrimesUITests.swift new file mode 100644 index 000000000..02d98efba --- /dev/null +++ b/Prime Numbers/Primes/PrimesUITests/PrimesUITests.swift @@ -0,0 +1,36 @@ +// +// PrimesUITests.swift +// PrimesUITests +// +// Created by Pratikbhai Patel on 6/13/16. +// Copyright © 2016 Pratikbhai Patel. All rights reserved. +// + +import XCTest + +class PrimesUITests: XCTestCase { + + override func setUp() { + super.setUp() + + // Put setup code here. This method is called before the invocation of each test method in the class. + + // In UI tests it is usually best to stop immediately when a failure occurs. + continueAfterFailure = false + // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. + XCUIApplication().launch() + + // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + } + + override func tearDown() { + // Put teardown code here. This method is called after the invocation of each test method in the class. + super.tearDown() + } + + func testExample() { + // Use recording to get started writing UI tests. + // Use XCTAssert and related functions to verify your tests produce the correct results. + } + +} diff --git a/Prime Numbers/SievePrimes.playground/Contents.swift b/Prime Numbers/SievePrimes.playground/Contents.swift index 21e500b79..3a416051a 100644 --- a/Prime Numbers/SievePrimes.playground/Contents.swift +++ b/Prime Numbers/SievePrimes.playground/Contents.swift @@ -18,7 +18,7 @@ func ..(left: (T, T.Stride), right: T) -> [T] { return [T](left.0.stride(through: right, by: left.1)) } -func primesTo(max: Int) -> [Int] { +func eratosthenes_sieve(max: Int) -> [Int] { assert(max > 1, "Prime numbers can only be above 1") print("Getting all primes under \(max)") let m = Int(sqrt(ceil(Double(max)))) @@ -38,7 +38,51 @@ func primesTo(max: Int) -> [Int] { return set.sortedArrayUsingDescriptors([NSSortDescriptor(key: "integerValue", ascending: true)]) as! [Int] } -let startDate = NSDate().timeIntervalSince1970 * 1000 -print(primesTo(50)) -let endDate = NSDate().timeIntervalSince1970 * 1000 +var startDate = NSDate().timeIntervalSince1970 * 1000 +print(eratosthenes_sieve(5000)) +var endDate = NSDate().timeIntervalSince1970 * 1000 +print("Prime generation time: \(endDate - startDate) ms.") + +func atkins_sieve(max: Int) -> [Int] { + var is_prime = [Bool](count: max + 1, repeatedValue: false) + is_prime[2] = true + is_prime[3] = true + let limit = Int(ceil(sqrt(Double(max)))) + for x in 1...limit { + for y in 1...limit { + var num = 4 * x * x + y * y + if (num <= max && (num % 12 == 1 || num % 12 == 5)) { + is_prime[num] = true + } + num = 3 * x * x + y * y + if (num <= max && num % 12 == 7) { + is_prime[num] = true + } + if (x > y) { + num = 3 * x * x - y * y + if (num <= max && num % 12 == 11) { + is_prime[num] = true + } + } + } + } + if limit > 5 { + for i in 5...limit { + if is_prime[i] { + for j in (i * i)..i..max { + is_prime[j] = false + } + } + } + } + var primesArray = [Int]() + for (idx, val) in is_prime.enumerate() { + if val == true { primesArray.append(idx) } + } + return primesArray +} + +startDate = NSDate().timeIntervalSince1970 * 1000 +print(atkins_sieve(5000)) +endDate = NSDate().timeIntervalSince1970 * 1000 print("Prime generation time: \(endDate - startDate) ms.") \ No newline at end of file From 0e81e07990ef7d1be811ec51baa90ac8b2ff8fa7 Mon Sep 17 00:00:00 2001 From: Pratikbhai Patel Date: Mon, 13 Jun 2016 10:31:58 -0400 Subject: [PATCH 03/10] Refactor Create singleton class --- Prime Numbers/PrimeGenerator.swift | 83 +++++++++++++++ .../Primes/Primes.xcodeproj/project.pbxproj | 7 ++ Prime Numbers/Primes/Primes/AppDelegate.swift | 100 +----------------- .../Primes/Primes/PrimeGenerator.swift | 83 +++++++++++++++ 4 files changed, 176 insertions(+), 97 deletions(-) create mode 100644 Prime Numbers/PrimeGenerator.swift create mode 100644 Prime Numbers/Primes/Primes/PrimeGenerator.swift diff --git a/Prime Numbers/PrimeGenerator.swift b/Prime Numbers/PrimeGenerator.swift new file mode 100644 index 000000000..7a2fa5367 --- /dev/null +++ b/Prime Numbers/PrimeGenerator.swift @@ -0,0 +1,83 @@ +// +// Operators.swift +// Primes +// +// Created by Pratikbhai Patel on 6/13/16. +// Copyright © 2016 Pratikbhai Patel. All rights reserved. +// + +import UIKit + +infix operator ^^ { associativity left precedence 160 } +func ^^ (radix: Int, power: Int) -> Int { + return Int(pow(CGFloat(radix), CGFloat(power))) +} + +infix operator .. {associativity left precedence 60 } + +func ..(left: T, right: T.Stride) -> (T, T.Stride) { + return (left, right) +} + +func ..(left: (T, T.Stride), right: T) -> [T] { + return [T](left.0.stride(through: right, by: left.1)) +} + +class PrimeGenerator { + + static let sharedInstance = PrimeGenerator() + + func eratosthenesPrimes(max: Int) -> [Int] { + let m = Int(sqrt(ceil(Double(max)))) + let set = NSMutableSet(array: 3..2..max) + set.addObject(2) + for i in (2..1..m) { + if (set.containsObject(i)) { + for j in i^^2..i..max { + set.removeObject(j) + } + } + } + return set.sortedArrayUsingDescriptors([NSSortDescriptor(key: "integerValue", ascending: true)]) as! [Int] + } + + func atkinsPrimes(max: Int) -> [Int] { + var is_prime = [Bool](count: max + 1, repeatedValue: false) + is_prime[2] = true + is_prime[3] = true + let limit = Int(ceil(sqrt(Double(max)))) + for x in 1...limit { + for y in 1...limit { + var num = 4 * x * x + y * y + if (num <= max && (num % 12 == 1 || num % 12 == 5)) { + is_prime[num] = true + } + num = 3 * x * x + y * y + if (num <= max && num % 12 == 7) { + is_prime[num] = true + } + if (x > y) { + num = 3 * x * x - y * y + if (num <= max && num % 12 == 11) { + is_prime[num] = true + } + } + } + } + if limit > 5 { + for i in 5...limit { + if is_prime[i] { + for j in (i * i)..i..max { + is_prime[j] = false + } + } + } + } + var primesArray = [Int]() + for (idx, val) in is_prime.enumerate() { + if val == true { primesArray.append(idx) } + } + return primesArray + } + +} \ No newline at end of file diff --git a/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj b/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj index 2f4958a28..0f9ab9fd7 100644 --- a/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj +++ b/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj @@ -14,6 +14,7 @@ 31900F4E1D0EF73700F8673F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 31900F4C1D0EF73700F8673F /* LaunchScreen.storyboard */; }; 31900F591D0EF73700F8673F /* PrimesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31900F581D0EF73700F8673F /* PrimesTests.swift */; }; 31900F641D0EF73700F8673F /* PrimesUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31900F631D0EF73700F8673F /* PrimesUITests.swift */; }; + 31900F761D0EF92E00F8673F /* PrimeGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31900F751D0EF92E00F8673F /* PrimeGenerator.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -47,6 +48,7 @@ 31900F5F1D0EF73700F8673F /* PrimesUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PrimesUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; 31900F631D0EF73700F8673F /* PrimesUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrimesUITests.swift; sourceTree = ""; }; 31900F651D0EF73700F8673F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 31900F751D0EF92E00F8673F /* PrimeGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrimeGenerator.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -99,6 +101,7 @@ children = ( 31900F431D0EF73700F8673F /* AppDelegate.swift */, 31900F451D0EF73700F8673F /* ViewController.swift */, + 31900F751D0EF92E00F8673F /* PrimeGenerator.swift */, 31900F471D0EF73700F8673F /* Main.storyboard */, 31900F4A1D0EF73700F8673F /* Assets.xcassets */, 31900F4C1D0EF73700F8673F /* LaunchScreen.storyboard */, @@ -256,6 +259,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 31900F761D0EF92E00F8673F /* PrimeGenerator.swift in Sources */, 31900F461D0EF73700F8673F /* ViewController.swift in Sources */, 31900F441D0EF73700F8673F /* AppDelegate.swift in Sources */, ); @@ -484,6 +488,7 @@ 31900F6A1D0EF73700F8673F /* Release */, ); defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; }; 31900F6B1D0EF73700F8673F /* Build configuration list for PBXNativeTarget "PrimesTests" */ = { isa = XCConfigurationList; @@ -492,6 +497,7 @@ 31900F6D1D0EF73700F8673F /* Release */, ); defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; }; 31900F6E1D0EF73700F8673F /* Build configuration list for PBXNativeTarget "PrimesUITests" */ = { isa = XCConfigurationList; @@ -500,6 +506,7 @@ 31900F701D0EF73700F8673F /* Release */, ); defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; diff --git a/Prime Numbers/Primes/Primes/AppDelegate.swift b/Prime Numbers/Primes/Primes/AppDelegate.swift index 6fd2b66de..d9aace8f1 100644 --- a/Prime Numbers/Primes/Primes/AppDelegate.swift +++ b/Prime Numbers/Primes/Primes/AppDelegate.swift @@ -8,128 +8,34 @@ import UIKit -infix operator ^^ { associativity left precedence 160 } -func ^^ (radix: Int, power: Int) -> Int { - return Int(pow(CGFloat(radix), CGFloat(power))) -} - -infix operator .. {associativity left precedence 60 } - -func ..(left: T, right: T.Stride) -> (T, T.Stride) { - return (left, right) -} - -func ..(left: (T, T.Stride), right: T) -> [T] { - return [T](left.0.stride(through: right, by: left.1)) -} - @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. performPrimesGeneration() return true } - func applicationWillResignActive(application: UIApplication) { - // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. - // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. - } - - func applicationDidEnterBackground(application: UIApplication) { - // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. - // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. - } - - func applicationWillEnterForeground(application: UIApplication) { - // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. - } - - func applicationDidBecomeActive(application: UIApplication) { - // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. - } - - func applicationWillTerminate(application: UIApplication) { - // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. - } - func performPrimesGeneration() { let primesTo = 1_000_000 - func eratosthenes_sieve(max: Int) -> [Int] { - assert(max > 1, "Prime numbers can only be above 1") - print("Getting all primes under \(max)") - let m = Int(sqrt(ceil(Double(max)))) - let set = NSMutableSet(array: 3..2..max) - set.addObject(2) - for i in (2..1..m) { - if (set.containsObject(i)) { - for j in i^^2..i..max { - set.removeObject(j) - } - } - } - return set.sortedArrayUsingDescriptors([NSSortDescriptor(key: "integerValue", ascending: true)]) as! [Int] - } + let primeGenerator = PrimeGenerator.sharedInstance var startDate = NSDate().timeIntervalSince1970 * 1000 - // print(eratosthenes_sieve(5000)) - let era_sieve = eratosthenes_sieve(primesTo) + let era_sieve = primeGenerator.eratosthenesPrimes(primesTo) var endDate = NSDate().timeIntervalSince1970 * 1000 print("Prime generation time for sieve of eratosthenes: \(endDate - startDate) ms.") - func atkins_sieve(max: Int) -> [Int] { - var is_prime = [Bool](count: max + 1, repeatedValue: false) - is_prime[2] = true - is_prime[3] = true - let limit = Int(ceil(sqrt(Double(max)))) - for x in 1...limit { - for y in 1...limit { - var num = 4 * x * x + y * y - if (num <= max && (num % 12 == 1 || num % 12 == 5)) { - is_prime[num] = true - } - num = 3 * x * x + y * y - if (num <= max && num % 12 == 7) { - is_prime[num] = true - } - if (x > y) { - num = 3 * x * x - y * y - if (num <= max && num % 12 == 11) { - is_prime[num] = true - } - } - } - } - if limit > 5 { - for i in 5...limit { - if is_prime[i] { - for j in (i * i)..i..max { - is_prime[j] = false - } - } - } - } - var primesArray = [Int]() - for (idx, val) in is_prime.enumerate() { - if val == true { primesArray.append(idx) } - } - return primesArray - } - startDate = NSDate().timeIntervalSince1970 * 1000 - // print(atkins_sieve(5000)) - let at_sieve = atkins_sieve(primesTo) + let at_sieve = primeGenerator.atkinsPrimes(primesTo) endDate = NSDate().timeIntervalSince1970 * 1000 print("Prime generation time for atkins sieve: \(endDate - startDate) ms.") print("they are equal \(era_sieve == at_sieve)") } - } diff --git a/Prime Numbers/Primes/Primes/PrimeGenerator.swift b/Prime Numbers/Primes/Primes/PrimeGenerator.swift new file mode 100644 index 000000000..7a2fa5367 --- /dev/null +++ b/Prime Numbers/Primes/Primes/PrimeGenerator.swift @@ -0,0 +1,83 @@ +// +// Operators.swift +// Primes +// +// Created by Pratikbhai Patel on 6/13/16. +// Copyright © 2016 Pratikbhai Patel. All rights reserved. +// + +import UIKit + +infix operator ^^ { associativity left precedence 160 } +func ^^ (radix: Int, power: Int) -> Int { + return Int(pow(CGFloat(radix), CGFloat(power))) +} + +infix operator .. {associativity left precedence 60 } + +func ..(left: T, right: T.Stride) -> (T, T.Stride) { + return (left, right) +} + +func ..(left: (T, T.Stride), right: T) -> [T] { + return [T](left.0.stride(through: right, by: left.1)) +} + +class PrimeGenerator { + + static let sharedInstance = PrimeGenerator() + + func eratosthenesPrimes(max: Int) -> [Int] { + let m = Int(sqrt(ceil(Double(max)))) + let set = NSMutableSet(array: 3..2..max) + set.addObject(2) + for i in (2..1..m) { + if (set.containsObject(i)) { + for j in i^^2..i..max { + set.removeObject(j) + } + } + } + return set.sortedArrayUsingDescriptors([NSSortDescriptor(key: "integerValue", ascending: true)]) as! [Int] + } + + func atkinsPrimes(max: Int) -> [Int] { + var is_prime = [Bool](count: max + 1, repeatedValue: false) + is_prime[2] = true + is_prime[3] = true + let limit = Int(ceil(sqrt(Double(max)))) + for x in 1...limit { + for y in 1...limit { + var num = 4 * x * x + y * y + if (num <= max && (num % 12 == 1 || num % 12 == 5)) { + is_prime[num] = true + } + num = 3 * x * x + y * y + if (num <= max && num % 12 == 7) { + is_prime[num] = true + } + if (x > y) { + num = 3 * x * x - y * y + if (num <= max && num % 12 == 11) { + is_prime[num] = true + } + } + } + } + if limit > 5 { + for i in 5...limit { + if is_prime[i] { + for j in (i * i)..i..max { + is_prime[j] = false + } + } + } + } + var primesArray = [Int]() + for (idx, val) in is_prime.enumerate() { + if val == true { primesArray.append(idx) } + } + return primesArray + } + +} \ No newline at end of file From 87ec25cfcf62cc28f4840270da3397544979920e Mon Sep 17 00:00:00 2001 From: Pratikbhai Patel Date: Mon, 20 Jun 2016 11:23:19 -0400 Subject: [PATCH 04/10] Update for Xcode 8 and Swift 3 --- .../Primes/Primes.xcodeproj/project.pbxproj | 14 ++++++++++++- Prime Numbers/Primes/Primes/AppDelegate.swift | 14 ++++++------- .../Primes/Primes/PrimeGenerator.swift | 20 +++++++++---------- .../Primes/PrimesTests/PrimesTests.swift | 2 +- 4 files changed, 31 insertions(+), 19 deletions(-) diff --git a/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj b/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj index 0f9ab9fd7..173ce4357 100644 --- a/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj +++ b/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj @@ -191,18 +191,21 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0730; - LastUpgradeCheck = 0730; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = "Pratikbhai Patel"; TargetAttributes = { 31900F3F1D0EF73700F8673F = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 0800; }; 31900F531D0EF73700F8673F = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 0800; TestTargetID = 31900F3F1D0EF73700F8673F; }; 31900F5E1D0EF73700F8673F = { CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 0800; TestTargetID = 31900F3F1D0EF73700F8673F; }; }; @@ -409,6 +412,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.Primes; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; }; name = Debug; }; @@ -420,6 +424,8 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.Primes; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; }; name = Release; }; @@ -431,6 +437,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.PrimesTests; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Primes.app/Primes"; }; name = Debug; @@ -443,6 +450,8 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.PrimesTests; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/Primes.app/Primes"; }; name = Release; @@ -454,6 +463,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.PrimesUITests; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_TARGET_NAME = Primes; }; name = Debug; @@ -465,6 +475,8 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = com.pratikpatel.PrimesUITests; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; TEST_TARGET_NAME = Primes; }; name = Release; diff --git a/Prime Numbers/Primes/Primes/AppDelegate.swift b/Prime Numbers/Primes/Primes/AppDelegate.swift index d9aace8f1..25341a1d6 100644 --- a/Prime Numbers/Primes/Primes/AppDelegate.swift +++ b/Prime Numbers/Primes/Primes/AppDelegate.swift @@ -13,7 +13,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. performPrimesGeneration() return true @@ -25,15 +25,15 @@ class AppDelegate: UIResponder, UIApplicationDelegate { let primeGenerator = PrimeGenerator.sharedInstance - var startDate = NSDate().timeIntervalSince1970 * 1000 + var startDate = Date() let era_sieve = primeGenerator.eratosthenesPrimes(primesTo) - var endDate = NSDate().timeIntervalSince1970 * 1000 - print("Prime generation time for sieve of eratosthenes: \(endDate - startDate) ms.") + var endDate = Date() + print("Prime generation time for sieve of eratosthenes: \(endDate.timeIntervalSince(startDate) * 1000) ms.") - startDate = NSDate().timeIntervalSince1970 * 1000 + startDate = Date() let at_sieve = primeGenerator.atkinsPrimes(primesTo) - endDate = NSDate().timeIntervalSince1970 * 1000 - print("Prime generation time for atkins sieve: \(endDate - startDate) ms.") + endDate = Date() + print("Prime generation time for atkins sieve: \(endDate.timeIntervalSince(startDate) * 1000) ms.") print("they are equal \(era_sieve == at_sieve)") } diff --git a/Prime Numbers/Primes/Primes/PrimeGenerator.swift b/Prime Numbers/Primes/Primes/PrimeGenerator.swift index 7a2fa5367..50389e607 100644 --- a/Prime Numbers/Primes/Primes/PrimeGenerator.swift +++ b/Prime Numbers/Primes/Primes/PrimeGenerator.swift @@ -20,29 +20,29 @@ func ..(left: T, right: T.Stride) -> (T, T.Stride) { } func ..(left: (T, T.Stride), right: T) -> [T] { - return [T](left.0.stride(through: right, by: left.1)) + return [T](stride(from: left.0, through: right, by: left.1)) } class PrimeGenerator { static let sharedInstance = PrimeGenerator() - func eratosthenesPrimes(max: Int) -> [Int] { + func eratosthenesPrimes(_ max: Int) -> [Int] { let m = Int(sqrt(ceil(Double(max)))) let set = NSMutableSet(array: 3..2..max) - set.addObject(2) + set.add(2) for i in (2..1..m) { - if (set.containsObject(i)) { + if (set.contains(i)) { for j in i^^2..i..max { - set.removeObject(j) + set.remove(j) } } } - return set.sortedArrayUsingDescriptors([NSSortDescriptor(key: "integerValue", ascending: true)]) as! [Int] + return set.sortedArray(using: [SortDescriptor(key: "integerValue", ascending: true)]) as! [Int] } - func atkinsPrimes(max: Int) -> [Int] { - var is_prime = [Bool](count: max + 1, repeatedValue: false) + func atkinsPrimes(_ max: Int) -> [Int] { + var is_prime = [Bool](repeating: false, count: max + 1) is_prime[2] = true is_prime[3] = true let limit = Int(ceil(sqrt(Double(max)))) @@ -74,10 +74,10 @@ class PrimeGenerator { } } var primesArray = [Int]() - for (idx, val) in is_prime.enumerate() { + for (idx, val) in is_prime.enumerated() { if val == true { primesArray.append(idx) } } return primesArray } -} \ No newline at end of file +} diff --git a/Prime Numbers/Primes/PrimesTests/PrimesTests.swift b/Prime Numbers/Primes/PrimesTests/PrimesTests.swift index eece41230..9bd8a8786 100644 --- a/Prime Numbers/Primes/PrimesTests/PrimesTests.swift +++ b/Prime Numbers/Primes/PrimesTests/PrimesTests.swift @@ -28,7 +28,7 @@ class PrimesTests: XCTestCase { func testPerformanceExample() { // This is an example of a performance test case. - self.measureBlock { + self.measure { // Put the code you want to measure the time of here. } } From 2dfcf10c13659fa4ab997b04892c8db4878846fe Mon Sep 17 00:00:00 2001 From: Pratikbhai Patel Date: Mon, 20 Jun 2016 11:48:27 -0400 Subject: [PATCH 05/10] Update and refactor with completion blocks and show results in textviews --- Prime Numbers/Primes/Primes/AppDelegate.swift | 21 +--------- .../Primes/Primes/Base.lproj/Main.storyboard | 40 ++++++++++++++++--- .../Primes/Primes/PrimeGenerator.swift | 11 +++-- .../Primes/Primes/ViewController.swift | 33 +++++++++++++-- 4 files changed, 73 insertions(+), 32 deletions(-) diff --git a/Prime Numbers/Primes/Primes/AppDelegate.swift b/Prime Numbers/Primes/Primes/AppDelegate.swift index 25341a1d6..2fa10d5a5 100644 --- a/Prime Numbers/Primes/Primes/AppDelegate.swift +++ b/Prime Numbers/Primes/Primes/AppDelegate.swift @@ -13,29 +13,10 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. - performPrimesGeneration() return true } - - func performPrimesGeneration() { - - let primesTo = 1_000_000 - - let primeGenerator = PrimeGenerator.sharedInstance - - var startDate = Date() - let era_sieve = primeGenerator.eratosthenesPrimes(primesTo) - var endDate = Date() - print("Prime generation time for sieve of eratosthenes: \(endDate.timeIntervalSince(startDate) * 1000) ms.") - - startDate = Date() - let at_sieve = primeGenerator.atkinsPrimes(primesTo) - endDate = Date() - print("Prime generation time for atkins sieve: \(endDate.timeIntervalSince(startDate) * 1000) ms.") - print("they are equal \(era_sieve == at_sieve)") - } - } diff --git a/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard b/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard index 3a2a49bad..4bac73530 100644 --- a/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard +++ b/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard @@ -1,22 +1,52 @@ - + - + + + - + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Prime Numbers/Primes/Primes/PrimeGenerator.swift b/Prime Numbers/Primes/Primes/PrimeGenerator.swift index 50389e607..cd6574305 100644 --- a/Prime Numbers/Primes/Primes/PrimeGenerator.swift +++ b/Prime Numbers/Primes/Primes/PrimeGenerator.swift @@ -27,7 +27,10 @@ class PrimeGenerator { static let sharedInstance = PrimeGenerator() - func eratosthenesPrimes(_ max: Int) -> [Int] { + + + + func eratosthenesPrimes(_ max: Int, completion:([Int]) -> ()){ let m = Int(sqrt(ceil(Double(max)))) let set = NSMutableSet(array: 3..2..max) set.add(2) @@ -38,10 +41,10 @@ class PrimeGenerator { } } } - return set.sortedArray(using: [SortDescriptor(key: "integerValue", ascending: true)]) as! [Int] + completion(set.sortedArray(using: [SortDescriptor(key: "integerValue", ascending: true)]) as! [Int]) } - func atkinsPrimes(_ max: Int) -> [Int] { + func atkinsPrimes(_ max: Int, completion:([Int]) -> ()) { var is_prime = [Bool](repeating: false, count: max + 1) is_prime[2] = true is_prime[3] = true @@ -77,7 +80,7 @@ class PrimeGenerator { for (idx, val) in is_prime.enumerated() { if val == true { primesArray.append(idx) } } - return primesArray + completion(primesArray) } } diff --git a/Prime Numbers/Primes/Primes/ViewController.swift b/Prime Numbers/Primes/Primes/ViewController.swift index c77924158..6c1188ee1 100644 --- a/Prime Numbers/Primes/Primes/ViewController.swift +++ b/Prime Numbers/Primes/Primes/ViewController.swift @@ -10,16 +10,43 @@ import UIKit class ViewController: UIViewController { + @IBOutlet weak var eraSieveTextView: UITextView! + @IBOutlet weak var atSieveTextView: UITextView! + override func viewDidLoad() { super.viewDidLoad() - // Do any additional setup after loading the view, typically from a nib. + performPrimesGeneration() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } - - + + func performPrimesGeneration() { + + let primesTo = 1_000 + + let primeGenerator = PrimeGenerator.sharedInstance + + var startDate = Date() + var endDate = Date() + var era_sieve = [Int]() + primeGenerator.eratosthenesPrimes(primesTo) { (primesArray) in + era_sieve = primesArray + endDate = Date() + print("Found \(era_sieve.count) primes in : \(endDate.timeIntervalSince(startDate) * 1000) ms.") + self.eraSieveTextView.text = era_sieve.description + } + + startDate = Date() + var at_sieve = [Int]() + primeGenerator.atkinsPrimes(primesTo) { (primesArray) in + at_sieve = primesArray + endDate = Date() + print("Found \(at_sieve.count) primes in : \(endDate.timeIntervalSince(startDate) * 1000) ms.") + self.atSieveTextView.text = at_sieve.description + } + } } From fed1b28daa138d87a638c99d4d724a889d453cf5 Mon Sep 17 00:00:00 2001 From: Pratikbhai Patel Date: Mon, 20 Jun 2016 13:21:40 -0400 Subject: [PATCH 06/10] Asynchronous calculations to free main thread --- Prime Numbers/PrimeGenerator.swift | 91 ++++++++++--------- .../Primes/Primes/Base.lproj/Main.storyboard | 4 +- .../Primes/Primes/PrimeGenerator.swift | 86 +++++++++--------- .../Primes/Primes/ViewController.swift | 30 +++--- 4 files changed, 113 insertions(+), 98 deletions(-) diff --git a/Prime Numbers/PrimeGenerator.swift b/Prime Numbers/PrimeGenerator.swift index 7a2fa5367..f4cc23ccc 100644 --- a/Prime Numbers/PrimeGenerator.swift +++ b/Prime Numbers/PrimeGenerator.swift @@ -20,64 +20,71 @@ func ..(left: T, right: T.Stride) -> (T, T.Stride) { } func ..(left: (T, T.Stride), right: T) -> [T] { - return [T](left.0.stride(through: right, by: left.1)) + return [T](stride(from: left.0, through: right, by: left.1)) } class PrimeGenerator { static let sharedInstance = PrimeGenerator() - - func eratosthenesPrimes(max: Int) -> [Int] { - let m = Int(sqrt(ceil(Double(max)))) - let set = NSMutableSet(array: 3..2..max) - set.addObject(2) - for i in (2..1..m) { - if (set.containsObject(i)) { - for j in i^^2..i..max { - set.removeObject(j) + private let eraQueue = DispatchQueue(label: "eraQueue") + private let atQueue = DispatchQueue(label: "atQueue") + + func eratosthenesPrimes(_ max: Int, completion:([Int]) -> ()){ + + eraQueue.async { + let m = Int(sqrt(ceil(Double(max)))) + let set = NSMutableSet(array: 3..2..max) + set.add(2) + for i in (2..1..m) { + if (set.contains(i)) { + for j in i^^2..i..max { + set.remove(j) + } } } + completion(set.sortedArray(using: [SortDescriptor(key: "integerValue", ascending: true)]) as! [Int]) } - return set.sortedArrayUsingDescriptors([NSSortDescriptor(key: "integerValue", ascending: true)]) as! [Int] } - func atkinsPrimes(max: Int) -> [Int] { - var is_prime = [Bool](count: max + 1, repeatedValue: false) - is_prime[2] = true - is_prime[3] = true - let limit = Int(ceil(sqrt(Double(max)))) - for x in 1...limit { - for y in 1...limit { - var num = 4 * x * x + y * y - if (num <= max && (num % 12 == 1 || num % 12 == 5)) { - is_prime[num] = true - } - num = 3 * x * x + y * y - if (num <= max && num % 12 == 7) { - is_prime[num] = true - } - if (x > y) { - num = 3 * x * x - y * y - if (num <= max && num % 12 == 11) { + func atkinsPrimes(_ max: Int, completion:([Int]) -> ()) { + atQueue.async { + var is_prime = [Bool](repeating: false, count: max + 1) + is_prime[2] = true + is_prime[3] = true + let limit = Int(ceil(sqrt(Double(max)))) + for x in 1...limit { + for y in 1...limit { + var num = 4 * x * x + y * y + if (num <= max && (num % 12 == 1 || num % 12 == 5)) { + is_prime[num] = true + } + num = 3 * x * x + y * y + if (num <= max && num % 12 == 7) { is_prime[num] = true } + if (x > y) { + num = 3 * x * x - y * y + if (num <= max && num % 12 == 11) { + is_prime[num] = true + } + } } } - } - if limit > 5 { - for i in 5...limit { - if is_prime[i] { - for j in (i * i)..i..max { - is_prime[j] = false + + if limit > 5 { + for i in 5...limit { + if is_prime[i] { + for j in (i * i)..i..max { + is_prime[j] = false + } } } } + var primesArray = [Int]() + for (idx, val) in is_prime.enumerated() { + if val == true { primesArray.append(idx) } + } + completion(primesArray) } - var primesArray = [Int]() - for (idx, val) in is_prime.enumerate() { - if val == true { primesArray.append(idx) } - } - return primesArray } - -} \ No newline at end of file +} diff --git a/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard b/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard index 4bac73530..fcb57098f 100644 --- a/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard +++ b/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard @@ -20,13 +20,13 @@ - + - + diff --git a/Prime Numbers/Primes/Primes/PrimeGenerator.swift b/Prime Numbers/Primes/Primes/PrimeGenerator.swift index cd6574305..f4cc23ccc 100644 --- a/Prime Numbers/Primes/Primes/PrimeGenerator.swift +++ b/Prime Numbers/Primes/Primes/PrimeGenerator.swift @@ -26,61 +26,65 @@ func ..(left: (T, T.Stride), right: T) -> [T] { class PrimeGenerator { static let sharedInstance = PrimeGenerator() - - - - + private let eraQueue = DispatchQueue(label: "eraQueue") + private let atQueue = DispatchQueue(label: "atQueue") + func eratosthenesPrimes(_ max: Int, completion:([Int]) -> ()){ - let m = Int(sqrt(ceil(Double(max)))) - let set = NSMutableSet(array: 3..2..max) - set.add(2) - for i in (2..1..m) { - if (set.contains(i)) { - for j in i^^2..i..max { - set.remove(j) + + eraQueue.async { + let m = Int(sqrt(ceil(Double(max)))) + let set = NSMutableSet(array: 3..2..max) + set.add(2) + for i in (2..1..m) { + if (set.contains(i)) { + for j in i^^2..i..max { + set.remove(j) + } } } + completion(set.sortedArray(using: [SortDescriptor(key: "integerValue", ascending: true)]) as! [Int]) } - completion(set.sortedArray(using: [SortDescriptor(key: "integerValue", ascending: true)]) as! [Int]) } func atkinsPrimes(_ max: Int, completion:([Int]) -> ()) { - var is_prime = [Bool](repeating: false, count: max + 1) - is_prime[2] = true - is_prime[3] = true - let limit = Int(ceil(sqrt(Double(max)))) - for x in 1...limit { - for y in 1...limit { - var num = 4 * x * x + y * y - if (num <= max && (num % 12 == 1 || num % 12 == 5)) { - is_prime[num] = true - } - num = 3 * x * x + y * y - if (num <= max && num % 12 == 7) { - is_prime[num] = true - } - if (x > y) { - num = 3 * x * x - y * y - if (num <= max && num % 12 == 11) { + atQueue.async { + var is_prime = [Bool](repeating: false, count: max + 1) + is_prime[2] = true + is_prime[3] = true + let limit = Int(ceil(sqrt(Double(max)))) + for x in 1...limit { + for y in 1...limit { + var num = 4 * x * x + y * y + if (num <= max && (num % 12 == 1 || num % 12 == 5)) { is_prime[num] = true } + num = 3 * x * x + y * y + if (num <= max && num % 12 == 7) { + is_prime[num] = true + } + if (x > y) { + num = 3 * x * x - y * y + if (num <= max && num % 12 == 11) { + is_prime[num] = true + } + } } } - } - if limit > 5 { - for i in 5...limit { - if is_prime[i] { - for j in (i * i)..i..max { - is_prime[j] = false + + if limit > 5 { + for i in 5...limit { + if is_prime[i] { + for j in (i * i)..i..max { + is_prime[j] = false + } } } } + var primesArray = [Int]() + for (idx, val) in is_prime.enumerated() { + if val == true { primesArray.append(idx) } + } + completion(primesArray) } - var primesArray = [Int]() - for (idx, val) in is_prime.enumerated() { - if val == true { primesArray.append(idx) } - } - completion(primesArray) } - } diff --git a/Prime Numbers/Primes/Primes/ViewController.swift b/Prime Numbers/Primes/Primes/ViewController.swift index 6c1188ee1..7f6e430f6 100644 --- a/Prime Numbers/Primes/Primes/ViewController.swift +++ b/Prime Numbers/Primes/Primes/ViewController.swift @@ -15,7 +15,7 @@ class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() - performPrimesGeneration() + self.performPrimesGeneration() } override func didReceiveMemoryWarning() { @@ -25,27 +25,31 @@ class ViewController: UIViewController { func performPrimesGeneration() { - let primesTo = 1_000 + let eraMax = 1_000_000 // max integer for Eratosthenes primes + let atMax = 1_000 // max integer for Atkins prime let primeGenerator = PrimeGenerator.sharedInstance - var startDate = Date() - var endDate = Date() + let eraStartDate = Date() var era_sieve = [Int]() - primeGenerator.eratosthenesPrimes(primesTo) { (primesArray) in + primeGenerator.eratosthenesPrimes(eraMax) { (primesArray) in era_sieve = primesArray - endDate = Date() - print("Found \(era_sieve.count) primes in : \(endDate.timeIntervalSince(startDate) * 1000) ms.") - self.eraSieveTextView.text = era_sieve.description + let eraEndDate = Date() + print("Found \(era_sieve.count) primes in : \(eraEndDate.timeIntervalSince(eraStartDate) * 1000) ms.") + DispatchQueue.main.async(execute: { + self.eraSieveTextView.text = era_sieve.description + }) } - startDate = Date() + let atStartDate = Date() var at_sieve = [Int]() - primeGenerator.atkinsPrimes(primesTo) { (primesArray) in + primeGenerator.atkinsPrimes(atMax) { (primesArray) in at_sieve = primesArray - endDate = Date() - print("Found \(at_sieve.count) primes in : \(endDate.timeIntervalSince(startDate) * 1000) ms.") - self.atSieveTextView.text = at_sieve.description + let atEndDate = Date() + print("Found \(at_sieve.count) primes in : \(atEndDate.timeIntervalSince(atStartDate) * 1000) ms.") + DispatchQueue.main.async(execute: { + self.atSieveTextView.text = at_sieve.description + }) } } } From 8219f2333ad1465ec6ed0bb0edda8c6afc5c9fb8 Mon Sep 17 00:00:00 2001 From: Pratikbhai Patel Date: Mon, 20 Jun 2016 14:15:50 -0400 Subject: [PATCH 07/10] Rearrange, add stuff --- Prime Numbers/README.md | 69 +++++++++++++++++++++++++++++++++++++++-- 1 file changed, 66 insertions(+), 3 deletions(-) diff --git a/Prime Numbers/README.md b/Prime Numbers/README.md index 2c3aa0081..31fa104cb 100644 --- a/Prime Numbers/README.md +++ b/Prime Numbers/README.md @@ -1,10 +1,12 @@ # Sieve Primes +## Sieve of Eratosthenes Goal: To quickly get an array of prime numbers with a specified limit using the Sieve of Eratosthenes. -The Sieve of Eratosthenes is an algorithm that finds all primes numbers up to any given limit. +The Sieve of Eratosthenes is an algorithm that finds all primes numbers up to any given limit by iteratively marking composites of each prime starting with multiples of 2. [Seeing this algorithm][1] in action is the best way to understand it. -Here's an implementation in Swift that should be easy to understand: + +### Implementation ``` func primesTo(max: Int) -> [Int] { @@ -30,10 +32,71 @@ print(primesArray) // prints [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] ``` ---*write some introduction to the Sieve of Eratosthenes*-- +## Sieve of Atkin + +Goal: To quickly get an array of prime numbers with a specified limit using the Sieve of Atkin. + +The Sieve of Atkin is an algorithm that finds all primes numbers up to any given limit. + +--*write some introduction to the Sieve of Atkin*-- + +### Implementation + +``` +func primesTo(max: Int) -> [Int] { + var is_prime = [Bool](count: max + 1, repeatedValue: false) + is_prime[2] = true + is_prime[3] = true + let limit = Int(ceil(sqrt(Double(max)))) + for x in 1...limit { + for y in 1...limit { + var num = 4 * x * x + y * y + if (num <= max && (num % 12 == 1 || num % 12 == 5)) { + is_prime[num] = true + } + num = 3 * x * x + y * y + if (num <= max && num % 12 == 7) { + is_prime[num] = true + } + if (x > y) { + num = 3 * x * x - y * y + if (num <= max && num % 12 == 11) { + is_prime[num] = true + } + } + } + } + if limit > 5 { + for i in 5...limit { + if is_prime[i] { + for j in (i * i)..i..max { + is_prime[j] = false + } + } + } + } + var primesArray = [Int]() + for (idx, val) in is_prime.enumerate() { + if val == true { primesArray.append(idx) } + } + return primesArray +} +``` +Put this code in a playground and test it like so: + +``` +let primesArray = primesTo(50) +print(primesArray) +// prints [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] +``` ## See also + +[1]:https://en.wikipedia.org/wiki/File:Sieve_of_Eratosthenes_animation.gif#/media/File:Sieve_of_Eratosthenes_animation.gif + [Sieve of Eratosthenes on Wikipedia](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) +[Sieve of Atkin on Wikipedia](https://en.wikipedia.org/wiki/Sieve_of_Atkin) + *Written for Swift Algorithm Club by Pratikbhai Patel* \ No newline at end of file From d007ca67e62164df23948e5ca95896b43dff97f4 Mon Sep 17 00:00:00 2001 From: Pratikbhai Patel Date: Thu, 14 Jul 2016 11:39:48 -0400 Subject: [PATCH 08/10] Make textviews un-editable --- Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard b/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard index fcb57098f..ba3790499 100644 --- a/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard +++ b/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard @@ -20,13 +20,13 @@ - + - + From 658599ed3f56037e8d4350f4d50cb3d9837846af Mon Sep 17 00:00:00 2001 From: Pratikbhai Patel Date: Thu, 14 Jul 2016 11:43:08 -0400 Subject: [PATCH 09/10] Some information about sieve of Atkin --- Prime Numbers/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Prime Numbers/README.md b/Prime Numbers/README.md index 31fa104cb..614e636de 100644 --- a/Prime Numbers/README.md +++ b/Prime Numbers/README.md @@ -38,7 +38,8 @@ Goal: To quickly get an array of prime numbers with a specified limit using the The Sieve of Atkin is an algorithm that finds all primes numbers up to any given limit. ---*write some introduction to the Sieve of Atkin*-- +In mathematics, the sieve of Atkin is a modern algorithm for finding all prime numbers up to a specified integer. Compared with the ancient sieve of Eratosthenes, which marks off multiples of primes, it does some preliminary work and then marks off multiples of squares of primes, thus achieving a better theoretical asymptotic complexity.[1][id] +[id]: https://en.wikipedia.org/wiki/Sieve_of_Atkin ### Implementation From 50ff5a200099f5564e331c9ee634b49795e30fe1 Mon Sep 17 00:00:00 2001 From: Jake Kirshner Date: Tue, 26 Sep 2017 12:17:52 -0600 Subject: [PATCH 10/10] update to radix sort tracking the largest value in the array on the first iteration of the bucket sort allows you to do one less loop and drops the need for a `done` variable. also updated the bucket initialization to use the `(repeatingElement: count:)` initializer and switched to using an iterator for looping through the buckets instead of accessing them based on the range loop. --- Radix Sort/radixSort.swift | 70 +++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 39 deletions(-) diff --git a/Radix Sort/radixSort.swift b/Radix Sort/radixSort.swift index 31a783db7..14650462d 100644 --- a/Radix Sort/radixSort.swift +++ b/Radix Sort/radixSort.swift @@ -5,43 +5,35 @@ */ -func radixSort(inout arr: [Int] ) { - - - let radix = 10 //Here we define our radix to be 10 - var done = false - var index: Int - var digit = 1 //Which digit are we on? - - - while !done { //While our sorting is not completed - done = true //Assume it is done for now - - var buckets: [[Int]] = [] //Our sorting subroutine is bucket sort, so let us predefine our buckets - - for _ in 1...radix { - buckets.append([]) - } - - - for number in arr { - index = number / digit //Which bucket will we access? - buckets[index % radix].append(number) - if done && index > 0 { //If we arent done, continue to finish, otherwise we are done - done = false - } - } - - var i = 0 - - for j in 0..