find the nth decagonal number in csharp

You can find the nth decagonal number, which is the nth number in the decagonal sequence, by using the formula: nth decagonal number = 3n^2 - 2n, where n is a positive integer.

To implement this formula in C#, you can define a function that takes an integer n as input and calculates the nth decagonal number using a loop. Here's an example implementation:

main.cs
public static int GetNthDecagonalNumber(int n)
{
    if (n <= 0)
    {
        throw new ArgumentException("n must be a positive integer");
    }
    
    int nthDecagonalNumber = 3 * n * n - 2 * n;
    
    return nthDecagonalNumber;
}
237 chars
12 lines

This function first checks if the input n is positive, and throws an ArgumentException if it's not. Then it calculates the nth decagonal number using the formula, and returns the result.

You can call this function with a positive integer n to get the nth decagonal number. For example:

main.cs
int nthDecagonalNumber = GetNthDecagonalNumber(5); // returns 133
66 chars
2 lines

This calculates the 5th decagonal number, which is 133.

gistlibby LogSnag