find the nth octagonal number in swift

To find the nth octagonal number in Swift, you can use the formula:

main.swift
n * (3*n - 2)
14 chars
2 lines

Where n is the index of the desired octagonal number.

Here's the implementation of the function that finds the nth octagonal number in Swift:

main.swift
func octagonalNumber(atIndex index: Int) -> Int {
    return index * (3 * index - 2)
}

// Example usage
print(octagonalNumber(atIndex: 1)) // Prints 1 (the first octagonal number)
print(octagonalNumber(atIndex: 2)) // Prints 8 (the second octagonal number)
print(octagonalNumber(atIndex: 3)) // Prints 21 (the third octagonal number)
335 chars
9 lines

Note that the index n starts from 1, so the first octagonal number is at index 1, the second at index 2, and so on.

gistlibby LogSnag