The approach is as follows:
Take the integer n
as the input of the function. The goal is to obtain the "squarest" table. As @John suggested we must calculate sqrt(n)
to get an idea of the dimensions. On the other hand we must calculate all the divisors of n
in order to do choose the nearest divisors to sqrt(n)
.
How do we choose the nearest low value? we can use this tip (Python): finding index of an item closest to the value in a list that's not entirely sorted and get the index of the nearest value in the list of divisors, let's say hIndex
.
Then the other dimension can be calculated dividing n
by divisors[hIndex]
or using a new index wIndex = hIndex + 1
and get divisors[wIndex]
.
The Python code is this (note that I used al lazy evaluation to find the divisors):
import numbers
from math import sqrt
def get_dimensions(n):
tempSqrt = sqrt(n)
divisors = []
currentDiv = 1
for currentDiv in range(n):
if n % float(currentDiv + 1) == 0:
divisors.append(currentDiv+1)
#print divisors this is to ensure that we're choosing well
hIndex = min(range(len(divisors)), key=lambda i: abs(divisors[i]-sqrt(n)))
wIndex = hIndex + 1
return divisors[hIndex], divisors[wIndex]