Created
October 16, 2019 19:21
-
-
Save knowncitizen/aae0e627ddf4319144b94a99fbbd7677 to your computer and use it in GitHub Desktop.
Find all the primes under <x>
This file contains hidden or 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" | |
| "math" | |
| ) | |
| var primes []int | |
| func makeRangeArray(min, max int) []int { | |
| a := make([]int, max-min+1) | |
| for i := range a { | |
| a[i] = min + i | |
| } | |
| return a | |
| } | |
| /* check primes below square root of a given number */ | |
| func checkPrimeSqrt(toCheck int) bool { | |
| /* no need to check 1 which is allegedly not a prime */ | |
| for i := 2; i <= int(math.Floor(math.Sqrt(float64(toCheck)))); i++ { | |
| if toCheck%i == 0 { | |
| return false | |
| } | |
| } | |
| /* return the value if it doesn't check against sqrt and > 1 */ | |
| return toCheck > 1 | |
| } | |
| func main() { | |
| fmt.Print("Enter a number to find the primes or enter: ") | |
| fmt.Println("") | |
| var n = 1000 | |
| fmt.Scanln(&n) | |
| a := makeRangeArray(0, n) | |
| for element := range a { | |
| if checkPrimeSqrt(element) { | |
| primes = append(primes, element) | |
| } | |
| } | |
| fmt.Println("Primes Array:") | |
| fmt.Println(primes) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment