Monday, October 26, 2020

You are not logged in.

I'd need to calculate the screen ratio of my screen

Basically I could write a handler calculating the greatest common factor, but since I'm not into math my routine would be longer, slower and I'd take some time to complete it.

Maybe somebody wrote a similar script already.

Offline

**robertfern****Member**- Registered: 2011-11-29
- Posts: 76

Here it is

## Applescript:

screenRatio(3840, 2160)

on screenRatio(h as integer, w as integer)

local c

set c to GCD(h, w)

display alert "Screen Ratio is " & (h div c) & " by " & (w div c)

return {h div c, w div c}

end screenRatio

on GCD(x as integer, y as integer)

local r

repeat while y ≠ 0

set r to x mod y

set x to y

set y to r

end repeat

return x as integer

end GCD

*Last edited by robertfern (2020-10-17 02:08:55 pm)*

Offline

**peavine****Member**- From:: Prescott, Arizona
- Registered: 2018-09-04
- Posts: 644

My math skills are pretty basic but I was interested by robertfern's solution, which works great. Out of curiosity I did a search on gcd and found the Wikipedia article on greatest common divisor. If I understand correctly, robertfern's script uses Euclid's algorithm.

Just as a project to work on, I decided to try and write a solution using brute-force AppleScript. It's only marginally slower than robertfern's script, although my script requires 4011 calculations and comparisons to achieve what robertfern's script accomplishes with only 4 calculations.

## Applescript:

set screenRatio to getRatio(3840, 2160)

on getRatio(x, y)

set xDivisors to getDivisors(x)

set yDivisors to getDivisors(y)

repeat with aGCD in xDivisors

if aGCD is in yDivisors then exit repeat

end repeat

return {x div aGCD, y div aGCD}

end getRatio

on getDivisors(theNumber)

set theDivisors to {}

repeat with i from theNumber to 1 by -1

if theNumber mod i = 0 then set end of theDivisors to i

end repeat

return theDivisors

end getDivisors

BTW, the calculations employed in robertferns script with Euclid's algorithm are:

3840 div 2160 = 1 with a remainder of 1680

2160 div 1680 = 1 with a remainder of 480

1680 div 480 = 3 with a remainder of 240

480 div 240 = 2 with a remainder of 0

Thus the GCD is 240 and the screen ratio is:

3840 div 240 = 16

2160 div 240 = 9

Also, just as a point of information which has no impact on the script's accuracy, the variables h and w in robertfern's script appear to be reversed (assuming a normally-sized computer screen).

*Last edited by peavine (2020-10-21 09:21:38 am)*

2018 Mac mini - macOS Catalina

Offline