javashapesareapolygons

Im not able to get area from n polygon in java


If you can explain to me, not only solve it, it will really be incredible.

FIRST: It's an exercise that my teacher gave me, it really does not have any value in my grades, but I'm trying to solve it, and I can't when I do the tests says

Input: n: 3 Output: 10 Expected Output: 13 Console Output: Empty

Here is the question:

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

A 1-interesting polygon is just 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 the 1-, 2-, 3- and 4-interesting polygons in the picture below.enter image description here


Solution

  • Firstly you have to find a mathematical way to find the area of your n-interesting polygon, than traspose to code. One way is to consider the Area function of a given n-polygon, such as
    Area(n)= (2n-1)^2-2*(n-1)(n)
    where (2n-1)^2 is the area of the square built over the n-int polygon with side=n+n-1(blue squares plus white squares), than I subtract only the area of white squares (one of this area is (n-1)n/2, I have to mul this with 4 sides so finally we have 2*(n-1)n )