find the nth square number in go

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.go
package main

import (
    "fmt"
    "math"
)

func nthSquareNumber(n int) int {
    // Calculate the nth square number using the formula n^2
    return int(math.Pow(float64(n), 2))
}

func main() {
    // Test the nthSquareNumber function with a few values
    fmt.Println(nthSquareNumber(1)) // expected output: 1
    fmt.Println(nthSquareNumber(2)) // expected output: 4
    fmt.Println(nthSquareNumber(3)) // expected output: 9
}
434 chars
19 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.

related categories

gistlibby LogSnag