Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sum of perimeter of all the squares in a rectangle using JavaScript
Problem: Suppose there are 5 squares embedded inside a rectangle like this −
The squares follow a Fibonacci-like pattern where each square's side length equals the sum of the two preceding squares. Their perimeter will be −
4 + 4 + 8 + 12 + 20 = 48 units
We are required to write a JavaScript function that takes in a number n and returns the sum of the perimeter if there are n squares embedded.
How It Works
The algorithm generates a Fibonacci sequence for square side lengths, then calculates the total perimeter:
- Start with two squares of side length 1
- Each subsequent square has side length = sum of previous two squares
- Calculate perimeter for each square (side × 4)
- Sum all perimeters
Example
Following is the code −
const num = 6;
const findPerimeter = (num = 1) => {
const arr = [1, 1];
let n = 0;
let sum = 2;
for(let i = 0; i < num - 1; i++){
n = arr[i] + arr[i + 1];
arr.push(n);
sum += n;
}
return sum * 4;
};
console.log(findPerimeter(num - 1));
Output
80
Step-by-Step Breakdown
const findPerimeterDetailed = (num = 1) => {
const sides = [1, 1]; // First two squares have side 1
console.log("Square sides:", sides);
// Generate remaining square sides using Fibonacci pattern
for(let i = 0; i < num - 1; i++){
let nextSide = sides[i] + sides[i + 1];
sides.push(nextSide);
console.log(`Square ${i + 3}: side = ${nextSide}`);
}
// Calculate total perimeter
let totalPerimeter = 0;
sides.forEach((side, index) => {
let perimeter = side * 4;
totalPerimeter += perimeter;
console.log(`Square ${index + 1}: perimeter = ${perimeter}`);
});
return totalPerimeter;
};
console.log("Final result:", findPerimeterDetailed(4));
Output
Square sides: [ 1, 1 ] Square 3: side = 2 Square 4: side = 3 Square 5: side = 5 Square 1: perimeter = 4 Square 2: perimeter = 4 Square 3: perimeter = 8 Square 4: perimeter = 12 Square 5: perimeter = 20 Final result: 48
Conclusion
This solution efficiently calculates the sum of perimeters using the Fibonacci sequence pattern. The key insight is that square sides follow Fibonacci numbers, and the total perimeter is 4 times the sum of all side lengths.
