Created
April 22, 2011 18:35
-
-
Save zrbecker/937331 to your computer and use it in GitHub Desktop.
Primes
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 ( | |
| "os" | |
| "fmt" | |
| "math" | |
| "strconv" | |
| ) | |
| /* | |
| * Determines if a number is prime. The second | |
| * argument must be a list of all primes lower | |
| * than n | |
| */ | |
| func isprime(n int, primes []int) bool { | |
| max := int(math.Sqrt(float64(n))) | |
| for j := 0; j < len(primes) && max >= primes[j]; j++ { | |
| if n % primes[j] == 0 { | |
| return false | |
| } | |
| } | |
| return true | |
| } | |
| /* | |
| * Returns a list of the first n prime numbers | |
| */ | |
| func nprimeslist(n int) []int { | |
| primes := []int{} | |
| for i := 2; len(primes) < n; i++ { | |
| if isprime(i, primes) { | |
| primes = append(primes, i) | |
| } | |
| } | |
| return primes | |
| } | |
| /* | |
| * Returns a list of the prime numbers less | |
| * than max | |
| */ | |
| func maxprimeslist(max int) []int { | |
| primes := []int{} | |
| for i := 2; i < max; i++ { | |
| if isprime(i, primes) { | |
| primes = append(primes, i) | |
| } | |
| } | |
| return primes | |
| } | |
| /* | |
| * Finds the nth prime number | |
| */ | |
| func nthprime(n int) int { | |
| prime := 0 | |
| if n >= 1 { | |
| primes := nprimeslist(n) | |
| prime = primes[n - 1] | |
| } | |
| return prime | |
| } | |
| func main() { | |
| if len(os.Args) != 2 { | |
| fmt.Printf("Usage: %s number\n", os.Args[0]) | |
| os.Exit(1) | |
| } | |
| n, _ := strconv.Atoi(os.Args[1]) | |
| prime := nthprime(n) | |
| fmt.Printf("The %dth prime is %d\n", n, prime) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment