Find the Nth Triacontakaihenagonal Number

Updated

Given a positive integer N, find the N-th triacontakaihenagonal number: the N-th polygonal number of a 31-sided polygon, the triacontakaihenagon.

What is a triacontakaihenagonal number?

Polygonal numbers count the dots in a growing family of regular polygons drawn from one shared corner, where each new polygon has one more dot on every side. For a polygon with s sides, the n-th polygonal number is

P(s, n) = ((s − 2)n² − (s − 4)n) / 2

A triacontakaihenagon has 31 sides. Putting s = 31 gives

T(n) = (29n² − 27n) / 2

which produces 1, 31, 90, 178, 295, …

The division is always exact: n(29n − 27) is even, because when n is odd, 29n − 27 is even.

Examples:

Input: N = 2
Output: 31
Explanation: T(2) = (29 × 4 − 27 × 2) / 2 = (116 − 54) / 2 = 31.

Input: N = 3
Output: 90
Explanation: T(3) = (261 − 81) / 2 = 90.

Approach

Apply the formula directly. A 64-bit integer type keeps 29n² from overflowing for larger n.

// N-th triacontakaihenagonal (31-gonal) number.
#include <stdio.h>

long long triacontakaihenagonal(long long n)
{
    return (29 * n * n - 27 * n) / 2;
}

int main(void)
{
    for (long long n = 1; n <= 5; n++) {
        printf("T(%lld) = %lld\n", n, triacontakaihenagonal(n));
    }
    return 0;
}

Output:

T(1) = 1
T(2) = 31
T(3) = 90
T(4) = 178
T(5) = 295

In Python, integers never overflow:

def triacontakaihenagonal(n: int) -> int:
    return (29 * n * n - 27 * n) // 2

for n in range(1, 6):
    print(f"T({n}) = {triacontakaihenagonal(n)}")

Complexity: O(1) time and O(1) space.

Comment
Next tutorial
Mithlesh Upadhyay Published 1 Dec 2024 · 2 min read

Mithlesh Upadhyay is a Computer Science and AI expert from Madhya Pradesh with strong academic background (BE in CSE and M.Tech in AI) and over six years of experience in technical content development. He has contributed tech articles, led teams, and worked in Full Stack Development and Data Science. He founded the w3colleges.org portal for learning resources.

Related tutorials