find the nth triangular number in go

To find the nth triangular number in Go, we need to use a mathematical formula. The nth triangular number is given by the formula:

main.go
Tn = (n * (n+1)) / 2
21 chars
2 lines

where Tn is the nth triangular number.

We can write a function in Go to calculate the nth triangular number as follows:

main.go
package main

import (
    "fmt"
    "math"
)

func nthTriangularNumber(n int) int {
    tn := (n * (n+1)) / 2
    return tn
}

func main() {
    n := 10
    tn := nthTriangularNumber(n)
    fmt.Println("The", n, "th triangular number is", tn)
}
246 chars
18 lines

In this example, we define a function nthTriangularNumber that takes an integer n as input and returns the nth triangular number. We use the formula mentioned above to calculate the triangular number and return it.

In the main function, we call the nthTriangularNumber function with n=10 as an example. The output printed to the console should be:

main.go
The 10 th triangular number is 55
34 chars
2 lines

Note that we have imported the math module to perform mathematical operations.

related categories

gistlibby LogSnag