Minimum perimeter of an area
Mathematica 34 26
Besides the explicit search there is a nice convergent series:
n = 27
{i=√n//.i_:>n/⌈n/⌊i⌋⌉,n/i}
{3, 9}
Three previous approaches with 34 characters:
{#,n/#}&@FixedPoint[n/⌈n/⌊#⌋⌉&,√n]
For[i=√n,i>(i=n/⌈n/⌊i⌋⌉),];{i,n/i}
f@i_:=f[f@i=n/⌈n/⌊i⌋⌉]
{i=f@√n,n/i}
ClearAll[f]
Visualization:
p = FixedPointList[n/⌈n/⌊#⌋⌉ &, Sqrt[n]];
Plot[n/x, {x, 0, 11}, GridLines -> {Range@n, Range@n},
AspectRatio -> Automatic, PlotRange -> {{0, 10.2}, {0, 7.2}},
Epilog -> {Red, Thickness[0.005],
Arrow[Transpose[{{n/p, ⌈p⌉}, {n/p, ⌊p⌋}, {⌈n/⌊p⌋⌉, ⌊p⌋}}, {2, 3, 1}]],
PointSize[0.02], Black, Point[{n/p[[-1]], p[[-1]]}]}]
GolfScript (21 chars)
:^,{)^\%!},.,2/=)^1$/
This takes the input as a number on the stack and leaves the result as two numbers on the stack.
For fair comparison with Howard's solution, taking input on stdin and giving output on stdout separated by newline is 23 chars:
~:^,{)^\%!},.,2/=)n^2$/
It works because this problem is trivial: it's just looking for the pair of factors closest to sqrt(area)
.
Online demo for a square; online demo for a non-square.
Python 2 (63 62)
n=input()
print[(i,n/i)for i in range(1,n)if i*i>=n/i*i==n][0]
This produces all pairs of integers (i, n/i) that could be the sides of the rectangle, starting from the first one greater or equal to the square root of n. It prints the first one.