- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Construct the Rectangle in C++
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 −
#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, ]
- Related Articles
- Construct a rectangle $ABCD$, where $AB =12 cm, BC=5 cm$.
- Rectangle Area in C++
- Perfect Rectangle in C++
- Maximal Rectangle in C++
- Rectangle Area II in C++
- Construct a rectangle whose one diagonal has length 5 cm and the angle between the diagonals is 50 degrees.
- Construct K Palindrome Strings in C++
- Circle and Rectangle Overlapping in C++
- Tiling a Rectangle with the Fewest Squares in C++
- How to construct custom attributes in C#?
- Program to construct Frequency Stack in C++
- Construct Binary Tree from String in C++
- Smallest Rectangle Enclosing Black Pixels in C++
- Construct Target Array With Multiple Sums in C++
- Program to print a rectangle pattern in C++
