find the nth hexagonal number in swift

To find the nth hexagonal number, we can use the formula: Hexagonal(n) = 2n^2 - n. Here's an implementation in Swift using a function that takes an integer n as input and returns the nth hexagonal number:

main.swift
func hexagonalNumber(_ n: Int) -> Int {
    return 2 * n * n - n
}

let nthHexagonalNumber = hexagonalNumber(5) // example usage: returns 91
141 chars
6 lines

The function takes an integer n as input and uses it to calculate the nth hexagonal number using the formula. The result is returned as an integer.

To use the function, simply call it with the desired value of n. In the example above, hexagonalNumber(5) returns the 5th hexagonal number, which is 91.

gistlibby LogSnag