Created
June 9, 2017 13:35
-
-
Save 0xcaff/136008869c19be4224b9a03a79b6d0bc to your computer and use it in GitHub Desktop.
A prime number generator using an incremental sieve of Eratosthenes. It's fast but memory bound.
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
package main | |
import ( | |
"fmt" | |
) | |
func main() { | |
// The number of primes to display before stopping. | |
maxPrimes := 1000000 | |
// The number of primes collected so far. | |
primesGot := 0 | |
// 2 is the first prime number | |
possiblePrime := 2 | |
// A mapping of composite numbers to their factors. | |
composites := map[int][]int{} | |
deleted := 0 | |
for { | |
// check if number is prime | |
primesOfComposite, isComposite := composites[possiblePrime] | |
if isComposite { | |
// the number is not prime. Move its factors to future composites. | |
for primeFactorIndex := range primesOfComposite { | |
primeFactor := primesOfComposite[primeFactorIndex] | |
composites[possiblePrime+primeFactor] = append( | |
composites[possiblePrime+primeFactor], primeFactor) | |
} | |
deleted++ | |
delete(composites, possiblePrime) | |
} else { | |
// the number is prime | |
// increment counter | |
primesGot++ | |
// stop if done | |
if primesGot >= maxPrimes { | |
fmt.Println(possiblePrime) | |
break | |
} | |
// add possiblePrime * possiblePrime as composite | |
composites[possiblePrime*possiblePrime] = append( | |
composites[possiblePrime*possiblePrime], possiblePrime) | |
} | |
possiblePrime++ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment