You need to take your width and height and make them into a fraction, then reduce it. To do that, you'll need to find the greatest common divisor of the numerator and denominator, and divide them both by that.
Now take the new fraction you got by dividing both the numerator and denominator by the greatest common divisor and do it again. Repeat this process until the greatest common divisor is 1. At that point you have your irreducible fraction and you can print it.
Another way to do it is to use Euclid's Algorithm.
Example:
Let's look at your top example, 1,000 x 1,200
1,000 / 1,200 = ?
We can see by examination that they both end in "00" so they're both divisible by 100. So start there:
1,000 ÷ 100 = 10
1,200 ÷ 100 = 12
Next, we see that 10 and 12 are both even, so they're both divisible by 2:
10 ÷ 2 = 5
12 ÷ 2 = 6
Finally, we see that 5 and 6 share no common factors besides 1. (This is because 5 is prime, so its only factors are 5 and 1. 6 has the factor 2 and 3, as well as 1 and 6.) So we have reached the end. The reduced fraction is 5 / 6.
One More Thing
You might also want to be able to detect cases of irrational ratios, such as the golden ratio, which is quite popular in visual arts. Such a ratio will not be possible to divide into small integers, so checking whether width / height
is within some small distance of the golden ratio may be sufficient.
width
/height
, so for 1000x1200, it's 1000/1200 = 0.8333... But if you want to print it out as a ratio with a format like 16:9, then it's slightly more complicated (though not much). But it's not clear from your question which one you're asking about. $\endgroup$