Reaching Points

hard math gcd greedy

Problem

Given start (sx,sy) and target (tx,ty) where each move sends (x,y) to (x+y,y) or (x,x+y), decide whether the target is reachable.

Inputsx=1, sy=1, tx=3, ty=5
Outputtrue
Reachable: (1,1)->(1,2)->(3,2)->(3,5).

def reachingPoints(sx, sy, tx, ty):
    while tx >= sx and ty >= sy:
        if tx == ty: break
        if tx > ty:
            if ty > sy: tx %= ty
            else: return (tx - sx) % ty == 0
        else:
            if tx > sx: ty %= tx
            else: return (ty - sy) % tx == 0
    return tx == sx and ty == sy
function reachingPoints(sx, sy, tx, ty) {
  while (tx >= sx && ty >= sy) {
    if (tx === ty) break;
    if (tx > ty) {
      if (ty > sy) tx %= ty;
      else return (tx - sx) % ty === 0;
    } else {
      if (tx > sx) ty %= tx;
      else return (ty - sy) % tx === 0;
    }
  }
  return tx === sx && ty === sy;
}
boolean reachingPoints(int sx, int sy, int tx, int ty) {
    while (tx >= sx && ty >= sy) {
        if (tx == ty) break;
        if (tx > ty) {
            if (ty > sy) tx %= ty;
            else return (tx - sx) % ty == 0;
        } else {
            if (tx > sx) ty %= tx;
            else return (ty - sy) % tx == 0;
        }
    }
    return tx == sx && ty == sy;
}
bool reachingPoints(int sx, int sy, int tx, int ty) {
    while (tx >= sx && ty >= sy) {
        if (tx == ty) break;
        if (tx > ty) {
            if (ty > sy) tx %= ty;
            else return (tx - sx) % ty == 0;
        } else {
            if (tx > sx) ty %= tx;
            else return (ty - sy) % tx == 0;
        }
    }
    return tx == sx && ty == sy;
}
Time: O(log(max(tx,ty))) Space: O(1)