Math problem

hello.
I need to dynamically stack rows and colums of squares. That is easy enough.

But i want to dynamically change the number of columns depending on the total number of squares. This way, i will always have a rectangular grid of squares.

I can do this by using a series of if…then statments to check the total number of squares, but this is not a good solution as it will not scale infinately nor is it very adaptable to different layouts.

I susupect that there is a way to find a relationship between the number of squares and the number of columns needed to keep things in a rectangular shape… but it hurts my head to keep trying to figure it out with my limited math skills.

Can some one with a bigger brain pleeeese help me with this?

Thanks.