This version seems a lot quicker:
function GetNearest2(desired, target)
d = mod(target, desired)
for i=0 to d
if mod(target, desired+i)=0 then exitfunction desired+i
if mod(target, desired-i)=0 then exitfunction desired-i
next
endfunction desired
The original averages 1000 runs in 0.016 secs (on my machine) and my version gets around 1000 in 0.0002 secs. You might want to run a few tests yourself on the output but it looks right to me.
EDIT: Test code
test = 500
do
st1# = timer()
for i=0 to 1000
if GetPointerPressed()
test = random(1, 999)
endif
GetNearest(test, 1000)
next
ft1# = timer()
time1# = ft1#-ft2#
st2# = timer()
for i=0 to 1000
if GetPointerPressed()
test = random(1, 999)
endif
GetNearest2(test, 1000)
next
ft2# = timer()
time2# = ft2#-st2#
Print("original took "+str(time1#) + ", new one took "+str(time2#))
Sync()
loop
function GetNearest(desired, target)
if mod(target, desired) = 0 then exitfunction desired
for up = desired to target
if mod(target, up) = 0 then exit
next up
for down = desired to 0 step - 1
if mod(target, down) = 0 then exit
next down
if abs(desired-up) > abs(desired-down) then exitfunction down
endfunction up
function GetNearest2(desired, target)
d = mod(target, desired)
for i=0 to d
if mod(target, desired+i)=0 then exitfunction desired+i
if mod(target, desired-i)=0 then exitfunction desired-i
next
endfunction desired
EDIT2:
Actually I get incorrect results occasionally. For 166 for example I should get 200. I need to go further than the d value... I will work on it
Using AppGameKit V2 Tier 1