find the nth octagonal number in csharp

To find the nth octagonal number in C#, we can either use a formula or iterate through the numbers until we find the nth octagonal number.

Using a formula is quicker and simpler than iteration. The formula for the nth octagonal number is:

main.cs
octagonalNumber = 3 * n * n - 2 * n;
37 chars
2 lines

where n is the position of the octagonal number.

Here's an implementation of the formula in C#:

main.cs
public static int GetNthOctagonalNumber(int n)
{
    return 3 * n * n - 2 * n;
}
81 chars
5 lines

Alternatively, we can use iteration to find the nth octagonal number. We can start with the first octagonal number, which is 1, and generate the next number by adding 8 to the previous number. We can repeat this process until we have the nth octagonal number.

Here's an implementation of the iterative approach in C#:

main.cs
public static int GetNthOctagonalNumber(int n)
{
    int octagonalNumber = 1;
    for (int i = 1; i < n; i++)
    {
        octagonalNumber += 8 * i;
    }
    return octagonalNumber;
}
186 chars
10 lines

gistlibby LogSnag