find area of n-interesting polygon
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)
As there are already coding examples, I will explain why the formula is n * n + (n-1) * (n-1)
- You need to see the graph diagonally
- You will notice that the sides are always n
- For example, if n=4, the shape has for 4 squares on each side, thus n * n
- However, if you notice, n * n does not account for all the squares. There are squares in between the once you accounted for
- Take away the square you have accounted with n * n, you will notice now that the side of the shape is now n-1
- Thus, you take into account of the squares in between, the formula is n * n + (n-1) * (n-1)
- 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.
The easiest solution to the problem in JavaScript:
function shapeArea(n) {
if(n<0) {
return false
}
return (n*n) + ((n-1)*(n-1))
}
console.log(shapeArea(1))
I think the last part where you have written the 'for' loop is dodgy. If you're already using recursion why do you need a 'for' loop? Nonetheless, I did it this way without using recursion:
def shapeArea(n):
if n == 1:
return 1
return n**2 + (n-1)**2
This is a formula to find an area of polygon for given n
def shapeArea(n):
return (n**2)+((n-1)**2)
shapeArea(3)
Output
13