I am a mobile developer and I have a problem and need to find a formula to get the dimensions of squares to fit inside a space. My problem is that I have a rectangle of dimensions lxw and need to fit n number of squares into it. Where n can change to any number from 2 up to 30 or more. While l and w can be any dimension but will mainly be in the range upward of 600x400. What I need is to fit exactly n number of squares into this space, the dimensions of the squares can go as small or as large as required.

Also I require the the number of rows and columns that will fit these squares in them. The squares will be displayed as evenly as possible across these rows and columns.

I have found a similar solution but I simply don't have the mathematics undestanding to get my head around the explanation. Also the explanation mentions that the grid is 'w squares wide, h squares high' however I don't know how many squares high and wide my screen will be, maybe I'm misunderstanding something? If someone could dumb this formula down for me it would be appreciated.

How can I calculate the size of a square block and the number of rows and columns needed to fit a known number of blocks on a page of known size?

  • $\begingroup$ Must they be strictly speaking squares, or can they be rectangles? $\endgroup$ – Alfred Yerger Jul 3 '15 at 1:11
  • $\begingroup$ Preferably squares but rectangles will suffice if absolutely necessary and if it makes the formula easier to read. $\endgroup$ – Nathan Jul 3 '15 at 1:13
  • $\begingroup$ Well my thought is that the dimensions of the screen might be limiting. The ratio of the number of squares on each side has to be the same as the ratio of the screen dimensions you'll be displaying on (of course you can remove some if you have to, but to make it fill the screen and look good, they have to be similar). $\endgroup$ – Alfred Yerger Jul 3 '15 at 1:14
  • $\begingroup$ I see your point with that, I think I will require gaps between my squares. I will re-work my question based off you advice. I have made edits to my original question but I think I still require another formula as mentioned in my edits. $\endgroup$ – Nathan Jul 3 '15 at 1:22
  • $\begingroup$ What if $n = 37$? You said you want exactly $n$ squares, but you didn't specify how you want the squares to be arranged... $\endgroup$ – user21820 Jul 3 '15 at 1:27

I ended up finding another question which basically answered my question. It has alot of maths behind it which I don't understand but he put a C code example so I was able to follow that and understand what I needed to do. Link is posted below

Algorithm to get the maximum size of n squares that fit into a rectangle with a given width and height


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.