Created
February 22, 2019 20:03
-
-
Save lordkebab/667ab86b38cdb1dc4a95c39bb62f5bb4 to your computer and use it in GitHub Desktop.
Generate primes using the Sieve of Eratosthenes
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" | |
"os" | |
"strconv" | |
) | |
func main() { | |
arg, _ := strconv.ParseInt(os.Args[1], 0, 0) | |
input := int(arg) | |
var primes []int | |
takeout := make([]bool, input+1) | |
// mark the multiples of half the slice as true | |
for j := 2; j <= input/2; j++ { | |
for k := 2; j*k <= input; k++ { | |
takeout[j*k] = true | |
} | |
} | |
// loop through the takeout slice and only print the indexes | |
// where the value is false | |
for e, v := range takeout { | |
if v == false && e >= 2 { | |
primes = append(primes, e) | |
} | |
} | |
fmt.Printf("List of primes up to %d: %v\n", input, primes) | |
if input == primes[len(primes)-1] { | |
fmt.Printf("%d is prime\n", input) | |
} else { | |
fmt.Printf("%d is NOT prime\n", input) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment