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/Eratosthenes_Sieve.swift b/Prime Numbers/Eratosthenes_Sieve.swift new file mode 100644 index 000000000..6859a8d88 --- /dev/null +++ b/Prime Numbers/Eratosthenes_Sieve.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/PrimeGenerator.swift b/Prime Numbers/PrimeGenerator.swift new file mode 100644 index 000000000..f4cc23ccc --- /dev/null +++ b/Prime Numbers/PrimeGenerator.swift @@ -0,0 +1,90 @@ +// +// 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](stride(from: left.0, through: right, by: left.1)) +} + +class PrimeGenerator { + + static let sharedInstance = PrimeGenerator() + 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]) + } + } + + 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 + } + } + } + } + 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.xcodeproj/project.pbxproj b/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj new file mode 100644 index 000000000..173ce4357 --- /dev/null +++ b/Prime Numbers/Primes/Primes.xcodeproj/project.pbxproj @@ -0,0 +1,526 @@ +// !$*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 */; }; + 31900F761D0EF92E00F8673F /* PrimeGenerator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31900F751D0EF92E00F8673F /* PrimeGenerator.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 = ""; }; + 31900F751D0EF92E00F8673F /* PrimeGenerator.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrimeGenerator.swift; 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 */, + 31900F751D0EF92E00F8673F /* PrimeGenerator.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 = 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; + }; + }; + }; + 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 = ( + 31900F761D0EF92E00F8673F /* PrimeGenerator.swift in Sources */, + 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)"; + SWIFT_VERSION = 3.0; + }; + 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)"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; + }; + 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)"; + SWIFT_VERSION = 3.0; + 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)"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; + 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)"; + SWIFT_VERSION = 3.0; + 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)"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; + 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; + defaultConfigurationName = Release; + }; + 31900F6B1D0EF73700F8673F /* Build configuration list for PBXNativeTarget "PrimesTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 31900F6C1D0EF73700F8673F /* Debug */, + 31900F6D1D0EF73700F8673F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 31900F6E1D0EF73700F8673F /* Build configuration list for PBXNativeTarget "PrimesUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 31900F6F1D0EF73700F8673F /* Debug */, + 31900F701D0EF73700F8673F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* 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..2fa10d5a5 --- /dev/null +++ b/Prime Numbers/Primes/Primes/AppDelegate.swift @@ -0,0 +1,22 @@ +// +// AppDelegate.swift +// Primes +// +// Created by Pratikbhai Patel on 6/13/16. +// Copyright © 2016 Pratikbhai Patel. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + // Override point for customization after application launch. + return true + } +} + 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..ba3790499 --- /dev/null +++ b/Prime Numbers/Primes/Primes/Base.lproj/Main.storyboard @@ -0,0 +1,55 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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/PrimeGenerator.swift b/Prime Numbers/Primes/Primes/PrimeGenerator.swift new file mode 100644 index 000000000..f4cc23ccc --- /dev/null +++ b/Prime Numbers/Primes/Primes/PrimeGenerator.swift @@ -0,0 +1,90 @@ +// +// 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](stride(from: left.0, through: right, by: left.1)) +} + +class PrimeGenerator { + + static let sharedInstance = PrimeGenerator() + 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]) + } + } + + 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 + } + } + } + } + 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 new file mode 100644 index 000000000..7f6e430f6 --- /dev/null +++ b/Prime Numbers/Primes/Primes/ViewController.swift @@ -0,0 +1,56 @@ +// +// ViewController.swift +// Primes +// +// Created by Pratikbhai Patel on 6/13/16. +// Copyright © 2016 Pratikbhai Patel. All rights reserved. +// + +import UIKit + +class ViewController: UIViewController { + + @IBOutlet weak var eraSieveTextView: UITextView! + @IBOutlet weak var atSieveTextView: UITextView! + + override func viewDidLoad() { + super.viewDidLoad() + self.performPrimesGeneration() + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + func performPrimesGeneration() { + + let eraMax = 1_000_000 // max integer for Eratosthenes primes + let atMax = 1_000 // max integer for Atkins prime + + let primeGenerator = PrimeGenerator.sharedInstance + + let eraStartDate = Date() + var era_sieve = [Int]() + primeGenerator.eratosthenesPrimes(eraMax) { (primesArray) in + era_sieve = primesArray + 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 + }) + } + + let atStartDate = Date() + var at_sieve = [Int]() + primeGenerator.atkinsPrimes(atMax) { (primesArray) in + at_sieve = primesArray + 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 + }) + } + } +} + 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..9bd8a8786 --- /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.measure { + // 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/README.md b/Prime Numbers/README.md new file mode 100644 index 000000000..614e636de --- /dev/null +++ b/Prime Numbers/README.md @@ -0,0 +1,103 @@ +# 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 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. + + +### Implementation + +``` +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] +``` + +## 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. + +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 + +``` +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 diff --git a/Prime Numbers/SievePrimes.playground/Contents.swift b/Prime Numbers/SievePrimes.playground/Contents.swift new file mode 100644 index 000000000..3a416051a --- /dev/null +++ b/Prime Numbers/SievePrimes.playground/Contents.swift @@ -0,0 +1,88 @@ +//: 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 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)))) + 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] +} + +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 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 @@ + + + + + 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..