[Math] Fit a rectangle inside a square while maintaining aspect ratio

algebra-precalculustrigonometry

I'm trying to scale down a rectangular screenshot to fit inside a smaller square. The rectangle is 640×352, and I want to fit it within a 200×200 square, while being as wide as possible (so its long side will be 200 also). And I want to retain its aspect ratio.

I came across this formula on Stack Overflow:

Given you have two images with sizes (w1, h1) and (w2, h2) and you
want to scale the second image to the same area as the first while
maintaining the aspect ratio, then

A = w1 * h1
new_w2 = sqrt(A * (w2 / h2))
new_h2 = A / new_w2

and it seems to be close to what I want, but since it actually creates another rectangle with matching area, it doesn't fit inside the square. It actually gives me a new rectangle with sides of 269.679944985 by 148.323969742 (which indeed comes out to 40000, the same as 200×200). I feel like I'm close but, for a programmer, I am really terrible at math. Any ideas will be appreciated.

In fact I'm so bad at math that I don't even know what to tag this. I'll go with trigonometry and edit once someone corrects me.

Best Answer

$\dfrac{640}{x}=200=>x=\dfrac{640}{200}=?\quad$ Then $\dfrac{352}x=?$