Construct the Rectangle in C++

C++Server Side ProgrammingProgramming

Suppose we have a specific rectangular web page area, our job is to design a rectangular web page, whose length L and width W that satisfies the following requirements −

• The area of the web page must equal to the given target area.

• The width W should not be larger than the length L, and L >= W.

• The difference between L and W should be as small as possible.

So, if the input is like 4, then the output will be [2,2], as the target area is 4, and all the possible ways to construct it are [1,4], [2,2], [4,1]. Here as per the requirement, it is 2, [1,4] is illegal; according to requirement 3, [4,1] is not proper compared to [2,2]. So the length L is 2, and the width W is 2.

To solve this, we will follow these steps −

• for initialize i := square root of area, when i > 0, update (decrease i by 1), do −

• if area mod i is same as 0, then −

• Define an array v, insert {area/i, i}

• return v

• return {-1, -1}

Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<auto> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector<int> constructRectangle(int area) {
for (int i = sqrt(area); i > 0; i--) {
if (area % i == 0) {
vector<int> v{ area / i, i };
return v;
}
}
return { -1, -1 };
}
};
main(){
Solution ob;
print_vector(ob.constructRectangle(4));
}

Input

4

Output

[2, 2, ]
Published on 10-Jun-2020 16:26:16