In: Computer Science
Given an integer named area which represents the area of a rectangle, write a function minPerimeter that calculates the minimum possible perimeter of the given rectangle, and prints the perimeter and the side lengths needed to achieve that minimum. The length of the sides of the rectangle are integer numbers. For example, given the integer area = 30, possible perimeters and side-lengths are: (1, 30), with a perimeter of 62 (2, 15), with a perimeter of 34 (3, 10), with a perimeter of 26 (5, 6), with a perimeter of 22 Thus, your function should print only the last line, since that is the minimum perimeter. Some example outputs: >>>minPerimeter(30) 22 where rectangle sides are 5 and 6. >>>minPerimeter(101) 204 where rectangle sides are 1 and 101. >>>minPerimeter(4564320) 8552 where rectangle sides are 2056 and 2220.
Code (Java):
public static void minPerimeter(int n)
{
int sumMin = Integer.MAX_VALUE;
int a=0,b=0;
for(int i=1 ;i<=Math.sqrt(n);i++)
{
if(n%i==0 )
{
if(2*(i+n/i) < sumMin)
{
sumMin=2*(i+n/i);
a = i;
b=n/i;
}
}
}
System.out.println(sumMin + " where rectangle sides are "+ a + "
and "+b+".");
}
Please refer to the screenshot of the code to understand the indentation of the code:
Outputs:
1. minPerimeter(30) :
2. minPerimeter(101) :
3. minPerimeter(4564320) :
For any doubts or questions comment below.