Unprimeable numbers: Difference between revisions
Content added Content deleted
m (Swift - print numbers with commas) |
m (Swift - simplified code) |
||
Line 2,480: | Line 2,480: | ||
init(size: Int) { |
init(size: Int) { |
||
array = Array(repeating: 0, count: (size + 31)/32) |
|||
} |
} |
||
func get(index: Int) -> Bool { |
func get(index: Int) -> Bool { |
||
let bit = UInt32(1) << (index & 31) |
let bit = UInt32(1) << (index & 31) |
||
return ( |
return (array[index >> 5] & bit) != 0 |
||
} |
} |
||
Line 2,491: | Line 2,491: | ||
let bit = UInt32(1) << (index & 31) |
let bit = UInt32(1) << (index & 31) |
||
if value { |
if value { |
||
array[index >> 5] |= bit |
|||
} else { |
} else { |
||
array[index >> 5] &= ~bit |
|||
} |
} |
||
} |
} |
||
Line 2,499: | Line 2,499: | ||
class PrimeSieve { |
class PrimeSieve { |
||
let composite: BitArray |
|||
init(size: Int) { |
init(size: Int) { |
||
composite = BitArray(size: size/2) |
|||
var p = 3 |
var p = 3 |
||
while p * p <= size { |
while p * p <= size { |
||
if ! |
if !composite.get(index: p/2 - 1) { |
||
let inc = p * 2 |
let inc = p * 2 |
||
var q = p * p |
var q = p * p |
||
while q <= size { |
while q <= size { |
||
composite.set(index: q/2 - 1, value: true) |
|||
q += inc |
q += inc |
||
} |
} |
||
Line 2,524: | Line 2,524: | ||
return number == 2 |
return number == 2 |
||
} |
} |
||
return ! |
return !composite.get(index: number/2 - 1) |
||
} |
} |
||
} |
} |