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.go21 chars2 lines
where Tn
is the nth triangular number.
We can write a function in Go to calculate the nth triangular number as follows:
main.go246 chars18 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.go34 chars2 lines
Note that we have imported the math
module to perform mathematical operations.
gistlibby LogSnag