find the nth triangular number in swift

To find the nth triangular number in Swift, we can use the formula Tn = n(n+1)/2. Here's the Swift code that implements this formula:

main.swift
func triangularNumber(_ n: Int) -> Int {
    return n * (n + 1) / 2
}

// Example usage:
print(triangularNumber(4)) // Prints 10
129 chars
7 lines

In this example, we pass 4 as the argument to the triangularNumber function, which returns the 4th triangular number 10.

The function simply calculates n * (n + 1)/2 and returns the result.

gistlibby LogSnag