In this **Leetcode Water and Jug problem solution**, You are given two jugs with capacities jug1Capacity and jug2Capacity liters. There is an infinite amount of water supply available. Determine whether it is possible to measure exactly targetCapacity liters using these two jugs.

If targetCapacity liters of water are measurable, you must have targetCapacity liters of water contained within one or both buckets by the end.

Operations allowed:

- Fill any of the jugs with water.
- Empty any of the jugs.
- Pour water from one jug into another till the other jug is completely full, or the first jug itself is empty.

## Problem solution in Python.

class Solution: def canMeasureWater(self, x: int, y: int, z: int) -> bool: x, y = (y, x) if y < x else (x, y) if x == z or y == z: return True if x == 0 or y == 0: return False if z > x + y: return False if z % x == 0: return True if z == x + y: return True if y % x == 0: return False if math.gcd(x,y) != 1 and z % math.gcd(x,y) != 0: return False if z % math.gcd(x,y) == 0: return True return True

## Problem solution in Java.

public boolean canMeasureWater(int x, int y, int z) { if(z>y && z>x)return false; if(z%gcd(x,y)==0)return true; return false; } public int gcd(int x,int y){ if(y==0)return x; return gcd(y,x%y); }

## Problem solution in C++.

class Solution { public: bool canMeasureWater(int j1, int j2, int t, bool o = true) { if (o && j1+j2 <= t) return (j1+j2 == t); if (j1 > 0) return canMeasureWater(j2%j1, j1, t, false); return (t%j2 == 0); } };

## Problem solution in C.

int gcd(int a,int b) { if(a==0) return b; else if(b==0) return a; return gcd(b,a%b); } bool canMeasureWater(int x, int y, int z){ return z == 0 || (z <= x + y && z % gcd(x, y) == 0); }

## 0 Comments