Home  >  Article  >  Backend Development  >  In C++, translate the following into Chinese: Find the rectangle with the smallest difference between length and width

In C++, translate the following into Chinese: Find the rectangle with the smallest difference between length and width

王林
王林forward
2023-09-16 13:21:09631browse

In C++, translate the following into Chinese: Find the rectangle with the smallest difference between length and width

Given a rectangular area as input. The goal is to find the sides of the rectangle that minimize the difference between length and width.

The area of ​​the rectangle = length * width.

Example

Input− Area = 100

Output− The rectangular side with the smallest difference:

Length = 10, width = 10

Explanation− Side of area = 100.

2-50, 4-25, 5-20, 10-10. The side with the smallest difference is 10-10, Difference = 0. As we all know, a square is a rectangle with all sides equal in length.

Input− Area = 254

Output− Sides of rectangle with minimum difference:

Length = 127, Width = 2

Explanation - The only possible minimum difference of sides to make a rectangle with area 254 is 127 and 2.

The method used in the program below is as follows

Here we will find the square root value of the area and traverse from there to 1 in order to find the value with the smallest difference, and area=input area.

  • Take the integer variable Area as input.

    li>
  • The function fragmentSides(int area1) accepts area1 and prints the side lengths of the rectangle, with the difference between length and width as small as possible.

  • Get integer length, width, tmp1.

  • Set tmp1=ceil(sqrt(area1))

  • Use for loop to traverse (int i = tmp1;i> 0; i --).

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

  • Use the break statement to stop iteration.

  • Print side length and width.

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

The above is the detailed content of In C++, translate the following into Chinese: Find the rectangle with the smallest difference between length and width. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete