find the nth hexagonal number in go

Here is how to find the nth hexagonal number in Go using the formula n(2n-1):

main.go
package main

import (
    "fmt"
    "math"
)

func nthHexagonalNumber(n int) int {
    return n * (2*n - 1)
}

func main() {
    nth := 7  // nth number to find
    hexagonal := nthHexagonalNumber(nth)
    fmt.Printf("The %dth hexagonal number is %d\n", nth, hexagonal)
}
273 chars
17 lines

In the above code, we define a function nthHexagonalNumber that receives an integer n and returns the nth hexagonal number using the formula n(2n-1). In the main function, we call nthHexagonalNumber passing the value of the nth number we want to find and print the result to the console.

gistlibby LogSnag