Rectangle with minimum possible difference between the length and the width in C++


Given an area of rectangle as input. The goal is to find the sides of a rectangle such that the difference between the length and breadth is minimum.

Area of Rectangle = length * breadth.

Examples

Input − Area = 100

Output −Side of Rectangle with minimum difference:

Length = 10, Breadth = 10

Explanation − Sides with area = 100.

2 - 50, 4 - 25, 5 - 20, 10 - 10. Sides with minimum difference are 10-10 with difference = 0. As we know tha square is a rectangle with equal length on all sides.

Input − Area = 254

Output − Side of Rectangle with minimum difference :

Length = 127, Breadth = 2

Explanation − Only possible sides with minimum difference yo make a rectangle with area 254 are 127 and 2.

Approach used in the below program is as follows

In this we will find the square root value of area and traverse from there to 1 in order to find values with minimum difference and area= input area.

  • Take the integer variable Area as input.

  • Function rectangleSides(int area1) takes area1 and prints the length of sides of Rectangle with minimum possible difference between the length and the width.

  • Take integers length, breadth, tmp1.

  • Set tmp1=ceil(sqrt(area1))

  • Traverse using for loop (int i = tmp1; i > 0; i--).

  • If (area1 % i == 0) then set length=area/i and breadth=i.

  • Stop iteration using the break statement.

  • Print sides length and breadth.

Example

#include <bits/stdc++.h>
using namespace std;
void rectangleSides(int area1){
   int length, breadth;
   int tmp1 = ceil(sqrt(area1));
   for (int i = tmp1; i > 0; i--) {
      if (area1 % i == 0) {

         length = ceil(area1 / i);
         breadth = i;
         break;
      }
   }
   cout<<"Sides of Rectangle with minimum difference :"<<endl;
   cout << "Length = " << length << ", Breadth = "   << breadth << endl;
}
int main(){
   int Area = 140;
   rectangleSides(Area);
   return 0;
}

Output

If we run the above code it will generate the following Output

Sides of Rectangle with minimum difference :
Length = 14, Breadth = 10

Updated on: 03-Nov-2021

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements