find the nth pentagonal number in csharp

To find the nth pentagonal number, we can use the formula:

Pn = n(3n-1)/2

Where Pn is the nth pentagonal number.

We can implement this formula in C# as follows:

main.cs
public static int GetNthPentagonalNumber(int n)
{
    return n * (3 * n - 1) / 2;
}
84 chars
5 lines

Here, we define a static method GetNthPentagonalNumber which takes an integer n as input representing the nth pentagonal number. The method calculates and returns the nth pentagonal number using the formula.

We can call this method to get the nth pentagonal number as follows:

main.cs
int nth = 5;
int pentagonal = GetNthPentagonalNumber(nth); // pentagonal = 35
78 chars
3 lines

Here, we define a variable nth to represent the desired nth pentagonal number (in this case, the 5th pentagonal number). We call the GetNthPentagonalNumber method and pass in nth as an argument to get the corresponding pentagonal number, which is stored in the pentagonal variable.

gistlibby LogSnag