shapeArea

Below we will define an n-interesting polygon. Your task is to find the area of the polygon for a given n.

A 1-interesting polygon is a square with a side of length 1. An n-interesting polygon is obtained by taking the (n-1)-interesting polygon and appending 1-interesting polygons to its rim, side by side. You can see 1-, 2-, 3-, 4- interesting polygons in the picture below :
Solution :

int shapeArea(int n)
{
    int sum = 0;
    for(int i = 1; i <= n - 1; i++)
    {
        sum += 2 * i - 1;
    }
    sum *= 2;
    sum += 2 * n - 1;
    return sum;
}

Comments

  1. return (int)Math.pow(n,2)+(int)Math.pow(n-1,2);

    ReplyDelete

Post a Comment