To find the nth square number in Go, we can create a function that takes an integer as an argument and returns the nth square number.
Here's the code:
main.go434 chars19 lines
In the nthSquareNumber
function, we use the math.Pow
function to calculate the nth square number. This function takes two arguments, a base number and an exponent, and returns the result of raising the base to the exponent power. Since we want the square of the input number n
, we raise n
to the second power using math.Pow(n, 2)
.
We then convert the result of math.Pow
from a float64
to an int
using int(math.Pow(float64(n), 2))
and return the result.
In the main
function, we test the nthSquareNumber
function with a few values and print the expected output.
gistlibby LogSnag