Im not able to get area from n polygon in java

2.2k Views Asked by At

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

3

There are 3 best solutions below

0
pippo On BEST ANSWER

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 )

0
Rijad Muhic On

You can do it in the simplest way. I set down calculations and found that for:

  • n = 1 => 1
  • n = 2 => 5
  • n = 3 => 13
  • n = 4 => 25
  • n = 5 => 41
  • n = 6 => 61 So when I did a calculation of the square of each number:
  • n = 1 => 1 -> 1*1 = 1
  • n = 2 => 5 -> 2*2 = 4, 5-4 = 1
  • n = 3 => 13 -> 3*3 = 9, 13-9=4
  • n = 4 => 25 -> 4*4 = 16, 25-16=9
  • n = 5 => 41 -> 5*5 = 25, 41-25=16
  • n = 6 => 61 -> 6*6 = 36, 61-36=25

Then I figured out formula : n^2 + (n-1)*(n-1)

0
KoalaD On

I did it a little more of a rudimentary way than others here.

I saw that lines above/below the middle follow the same formula (2n - 1) for the area.

The top and the bottom are mirrored. So, I looped only half of the height. Each time it looped I added (2n-1) to the total area then I subtracted 1 from n.

After the loop is finished I multiplied the area by 2 to get the bottom/top area. I then combined that with the middle area.

Hope that helps!