find the nth octagonal number in python

To find the nth octagonal number, we can use the following formula:

Octagonal(n) = 3n^2 - 2n

We can write a Python function to implement this formula and return the nth octagonal number.

main.py
import math

def nth_octagonal_number(n):
    """
    Find the nth octagonal number.
    """
    if n < 1:
        return None

    return 3 * n ** 2 - 2 * n

# Example usage
print(nth_octagonal_number(5)) # Output: 141
220 chars
14 lines

In this implementation, we first check if the input number n is greater than or equal to 1. If n is less than 1, we return None as there is no such thing as a 0th or negative nth octagonal number.

Otherwise, we simply apply the formula to find the nth octagonal number and return the result. In the above example usage, we are finding the 5th octagonal number which should be 141.

gistlibby LogSnag