Created
December 6, 2013 18:52
-
-
Save keipes/7830181 to your computer and use it in GitHub Desktop.
Optimized version of `primes less than n` written in Go
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"; | |
"log"; | |
"math"; | |
) | |
func IsPrime(target int) bool { | |
isPrime := true; | |
if target > 2 { | |
for num := 2; num < target; num++ { | |
if target % num == 0 { | |
isPrime = false | |
break | |
} | |
} | |
} | |
return isPrime | |
} | |
func FastIsPrime(target int) bool { | |
/* Only check against numbers less than the square root of our target plus one. */ | |
isPrime := true; | |
if target > 2 { | |
for num := 2; num < int(math.Sqrt(float64(target))) + 1; num++ { | |
if target % num == 0 { | |
isPrime = false | |
break | |
} | |
} | |
} | |
return isPrime | |
} | |
func GetPrimesLessThan(target int) { | |
numFound := 0 | |
for num := 2; num <= target; num++ { | |
if FastIsPrime(num) { | |
numFound++ | |
// fmt.Printf("%v\n", num) | |
} | |
} | |
fmt.Printf("Found %v primes below %v.\n",numFound, target) | |
} | |
func main() { | |
args := os.Args | |
target, err := strconv.Atoi(args[1]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
GetPrimesLessThan(target) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment