Skip to content

Instantly share code, notes, and snippets.

@a40yostudent
Created January 3, 2023 16:16
Show Gist options
  • Save a40yostudent/71628f44454c0780ae9ee97055c56038 to your computer and use it in GitHub Desktop.
Save a40yostudent/71628f44454c0780ae9ee97055c56038 to your computer and use it in GitHub Desktop.
Calculate Brun’s constant
@main
public struct Brun {
static let primesLength = 100000000
public static func main() {
// proven that all primes are in the form '6k +/- 1'
// this is a switch to advance the candidate of +2 or +4, to be xored with 1 every loop.
var form_6k_pm1 = false
var primes = Array(repeating: 0, count: primesLength)
primes[0] = 2
primes[1] = 3
primes[2] = 5
primes[3] = 7
primes[4] = 11
primes[5] = 13
var candidate = 17
var firstEmptyIndex = 6
while primes.last == 0 {
var index = 1
var isPrime = true
var factor = primes[index]
while isPrime && (factor * factor <= candidate) {
if candidate % factor == 0 {
isPrime = false
}
index += 1
factor = primes[index]
}
if isPrime {
primes[firstEmptyIndex] = candidate
firstEmptyIndex += 1
}
candidate += (form_6k_pm1 ? 4 : 2)
form_6k_pm1.toggle()
}
print("The \(primesLength)th prime is \(String(describing: primes.last))")
var brun = 0.0
for i in 1..<primesLength {
let twin1 = primes[i]
let twin2 = primes[i-1]
if twin1 == twin2 + 2 {
brun += (1/Double(twin1)) + (1/Double(twin2))
}
}
print(brun)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment