calculating thumbnail icon size


The topic may hopefully not be misleading. So here is problem:
I have a canvas which is let’s say 400x300 and (n) numbers of pictures of the same size which I like to rescale and
fit into it. The icons/thumbs should be rescaled so that all elements can fit like a table.
0 1 2 3 4
5 6 7 x x
x x x x x

I know there’s a limit when (n) to big so that with/height is less then 1px or so.
I am not able to solve that optimal. I’m currently calculating with a fixed row/column which leads to gaps doesn’t
looks goods for less elements.