Last active
January 27, 2019 20:35
-
-
Save mattt/d725a54f9b5aa6a3eaa425f4e1f18f78 to your computer and use it in GitHub Desktop.
Sieve of Eratosthenes with Accelerate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Calculate prime numbers in a given range | |
// using Sieve of Eratosthenes | |
import Accelerate | |
var primes: [Int] = [] | |
let range = 0...999 | |
var numbers = range.map(Float.init) | |
for n in range.dropLast() { | |
guard numbers[n] > 1 else { continue } | |
defer { primes.append(n) } | |
// Clear vector elements with given stride | |
// (i.e. set value to 0) | |
vDSP_vclr(&numbers, | |
numericCast(n), | |
numericCast(numbers.count / n)) | |
} | |
print(primes) |
Here is what I figured out:
numbers.count
is the last number in therange + 1
, so the number of elements calculation should be:(numbers.count - 1) / n
- there is no need to
dropLast
- to account for the zeroth element behavior, it's easy enough to start
vDSP_vclr
at&numbers[n]
.
I'll post a modified version in a few.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My understanding of the
stride
parameter is that a value of2
, means "clear every 2nd (even) element",3
means "clear every 3rd element)", etc. So yes, it clearsnumbers[0]
each time, but that's fine because numbers < 2 aren't considered.To clarify my point from before, I wonder if always rounding up
numbers.count / n
(like withceil
) would solve the problem. Adding 1 as you described would have the same effect (at least for any divisions that are rounded down.