Water and Jug Problem

medium math gcd

Problem

Given two jugs of capacity x and y and a target z, can we measure exactly z liters? Allowed operations: fill, empty, pour between jugs.

Inputx = 3, y = 5, target = 4
Outputtrue
Bézout: any multiple of gcd(x, y) reachable up to x + y is measurable.

from math import gcd

def can_measure_water(x, y, target):
    if target == 0:
        return True
    if x + y < target:
        return False
    return target % gcd(x, y) == 0
function canMeasureWater(x, y, target) {
  if (target === 0) return true;
  if (x + y < target) return false;
  const gcd = (a, b) => b === 0 ? a : gcd(b, a % b);
  return target % gcd(x, y) === 0;
}
class Solution {
    public boolean canMeasureWater(int x, int y, int target) {
        if (target == 0) return true;
        if ((long)x + y < target) return false;
        return target % gcd(x, y) == 0;
    }
    int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }
}
bool canMeasureWater(int x, int y, int target) {
    if (target == 0) return true;
    if ((long)x + y < target) return false;
    return target % __gcd(x, y) == 0;
}
Time: O(log(min(x, y))) Space: O(1)