If the number of rectangles was unlimited, you would need to find the LCD (Least Common Denominator) of Sw and Sh. Then you could divide it by Sw and Sh to find the horizontal and vertical count.
Since it is limited, it's different. Do I understand correctly that you have to use up ALL the rectangles and the result has to be a rectangle as well? I'll assume so.
In such a case you don't really have that many choices on how to arrange the rectangles. There are only that many integer-pairs that give N when multiplied together.
In your case I'd try to find all possible such pairs of integers (use a simple FOR loop) and see which one is closest to a square. In the FOR loop notice, that you have to check only up to sqrt(N), because every integer-pair that you find after that will be the same as one you have already found, just in reverse.