find the nth heptagonal number in go

To find the nth heptagonal number (a figurate number that represents a heptagon), we can use the formula:

H₇(n) = 5n² - 3n

Here is the implementation of the formula in Go:

main.go
package main

import (
	"fmt"
	"math"
)

func heptagonalNumber(n int) int {
	return (5 * int(math.Pow(float64(n), 2))) - (3 * n)
}

func main() {
	n := 10
	fmt.Printf("The %dth heptagonal number is %d\n", n, heptagonalNumber(n))
}
231 chars
16 lines

In this code snippet, we define a function heptagonalNumber that takes an integer n as input and returns the nth heptagonal number. We use the math.Pow function from the math package to calculate .

In the main function, we call the heptagonalNumber function with a value of n = 10 and print out the result. You can modify the value of n to find the nth heptagonal number for a different value of n.

gistlibby LogSnag