Reputation: 35
Description
Find the smallest possible perimeter for a rectangle and its dimensions. I am not sure how to implement this in python when the area is not a perfect square.
Sample Input
Area in units
100
15
195
Sample Output
Minimum perimeter is 40 with dimensions 10 x 10
Minimum perimeter is 16 with dimensions 3 x 5
Minimum perimeter is 56 with dimensions 13 x 15
My Code
My code can only find the minimum if the area is a perfect square root.
The code take multiple inputs and terminates if 0 is inputed.
import math
zero = False
while not zero:
newInput = int(input())
if newInput == 0:
zero = True
else:
l = math.sqrt(newInput)
sq = l * l
if sq == l:
print('Minimum perimeter is ' + l + ' with dimensions ' + l + ' x ' + l)
else:
# I don't know how to find minimum perimeter and its dimensions, when the integer is not a perfect square
Upvotes: 2
Views: 1314
Reputation: 83527
From your examples, I assume that the length and width must be integer values. Otherwise, you could just take the squareroot of the area and you are finished.
With this assumption, we note that A = l*w
. In otherwords, the length and width are factors of the area. So the first step is to create a list of all factors of the area. My suggestion is to start by printing out this list for a given number.
Once you have that much, you can use the same loop to find the minimum perimeter. If a pair of numbers for the length and width are factors of the area, then you calculate the perimeter. If it is smaller than any perimeter you have calculated so far, then save it. When the loop is finished, print out the minimum perimeter you found.
Notice how I am describing the process to solve this problem in words. This is always the first step in writing any computer program. You should only start writing code after you have a firm understanding of the steps in this way.
Upvotes: 1
Reputation: 781068
Starting with the square root of the area, search for the next lowest integer that evenly divides the area. Divide the area by this to get the corresponding width. Then add 2l + 2w
to get the perimiter.
while True:
newInput = int(input())
if newInput == 0:
break
else:
l = floor(math.sqrt(newInput))
while newInput % l ! = 0:
l -= 1
w = newInput / l
print('Minimum perimiter is %.2f with dimensions %.2f x %.2f' % (2 * l + 2 * w, l, w))
Upvotes: 1