Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find area of n-interesting polygon

Consider:

Enter image description here

I am trying to find the area of an n-interesting polygon, where (n=1, A=1, n=2, A=5, n=3, A=13, n=4, A=25, and so on). So the formula for an n-interesting polygon is the area of an (n-1)-interesting polygon+(n-1)*4. When running the program, a hidden test shows that the code is wrong. What is wrong with my code?

def shapeArea(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    for i in range(2, n+1):
        return (shapeArea(n-1) + (n-1)*4)
like image 662
M-M Avatar asked Mar 14 '18 05:03

M-M


2 Answers

I found the formula without the recursion. The test went through fine.

def shapeArea(n):
    if n>=10**4 or n<1:
        return False

    return (n**2+(n-1)**2)
like image 92
M-M Avatar answered Nov 05 '22 21:11

M-M


As there are already coding examples, I will explain why the formula is n * n + (n-1) * (n-1)

  1. You need to see the graph diagonally
  2. You will notice that the sides are always n
  3. For example, if n=4, the shape has for 4 squares on each side, thus n * n
  4. However, if you notice, n * n does not account for all the squares. There are squares in between the once you accounted for
  5. Take away the square you have accounted with n * n, you will notice now that the side of the shape is now n-1
  6. Thus, you take into account of the squares in between, the formula is n * n + (n-1) * (n-1)
  7. Example: if n = 4, the outer square is 4 * 4 = 16. Then take away the area you have just calculated, the inner squares is 3 * 3 = 9. Add together, you get 25.
like image 29
ProFire Avatar answered Nov 05 '22 21:11

ProFire