Sorry for not being clearer.
I have an area, let’s call this the screen. Width and height of the area are fixed.
I have a variable number of square images, each of them are the same size but I can control this size as long as they are square.
When I say “calculate the optimal size for each image” I mean that I want to find the image size so that when the images are stacked, column by column or row by row, gives the greatest coverage of the screen without crossing the screen boundaries.
So let’s do an example of manual optimization. I have a screen of w=100 and h=100. I have 10 images. If I size them at 20x20 I will be able to fit 25 in the 100x100 area. Since I only have 10, I am wasting space and should increase the size. If I size them at 30x30 I will be able to fit 9 in the 100x100 area. Now I have 1 leftover, so I should decrease the size. If I size them at 25x25 I will be able to fit 16 in the 100x100 area. It appears that the 25 is the optimal size.