find the nth prime number in go

To find the nth prime number in Go, we can implement a simple algorithm that generates all prime numbers up to a certain limit and then returns the nth one. Here's one possible approach:

main.go
package main

import "fmt"

func nthPrime(n int) int {
    if n == 1 {
        return 2
    }
    count := 1
    num := 3
    for {
        if isPrime(num) {
            count++
        }
        if count == n {
            return num
        }
        num += 2
    }
}

func isPrime(n int) bool {
    if n < 2 {
        return false
    }
    for i := 2; i*i <= n; i++ {
        if n%i == 0 {
            return false
        }
    }
    return true
}

func main() {
    n := 10
    fmt.Printf("The %dth prime number is %d\n", n, nthPrime(n))
}
546 chars
38 lines

Here, we first check if n is 1, in which case the first prime number (2) is returned. Otherwise, we set a counter to 1 and a starting number to 3 (since 2 is already accounted for). We then loop through odd numbers, checking if each one is prime using the isPrime function we define. If we find a prime, we increment our counter. If our counter reaches n, we return the current number as the nth prime. If not, we continue looping to find the next prime number.

The isPrime function works by checking if a given number n is divisible by any number from 2 to the square root of n. If it is, false is returned, indicating that n is not prime. If no divisors are found, true is returned.

gistlibby LogSnag