ActiveState Code

Recipe 146036: Find smallest square to fit input.


A procedure from the bag of utilities used by Jeff Hobbs. Given an integer number it finds the smallest square greater than the input. A possible application for this is when a discrete number of items have to be displayed in a table. Using this returns the number of columns/rows for the table to fit all items.

Tcl
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# get_square_size --
#   gets the minimum square size for an input
# Arguments:
#   num		number
# Returns:
#   returns smallest square size that would fit number
#
proc get_square_size num {
    set i 1
    while {($i*$i) < $num} { incr i }
    return $i
}

Comments

  1. 1. At 12:39 p.m. on 18 nov 2003, Keith Vetter said:

    Simpler version. Why not just:

    proc get_square_size {num} {
      return [expr {int(sqrt($num))}]
    }
    

Sign in to comment