Bézout’s identity is number-theoretic conclusion that should be remembered.

if \(gcd(a_{1},a_{2},\ldots ,a_{n})=d\)

then there are integers \(x_{1},x_{2},\ldots ,x_{n}\) such that

$$d=a_{1}x_{1}+a_{2}x_{2}+\cdots +a_{n}x_{n}$$

has the following properties:

  • \(d\) is the smallest positive integer of this form
  • every number of this form is a multiple of \(d\)

We can apply it with the following problem.

Description

LeetCode 365


You are given two jugs with capacities x and y litres. There is an infinite amount of water supply available. You need to determine whether it is possible to measure exactly z litres using these two jugs.

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

Operations allowed:

  • Fill any of the jugs completely 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.

Example 1: (From the famous “Die Hard” example)

Input: x = 3, y = 5, z = 4
Output: True

Example 2:

Input: x = 2, y = 6, z = 5
Output: False

Analysis

Actually, the problem can be transformed a math problem.

Check if there are integers \(m\) and \(n\) that satisfies

$$mx+ny=z$$

With Bézout’s identity, we know it is true that \(mx+ny=gcd(x,y)\). So if there is a integer i that satisfies\(z=gcd(x,y)*i\), it is possible to measure exactly z litres using these two jugs.

Solution

class Solution {
    public boolean canMeasureWater(int x, int y, int z) {
        if(x+y<z) return false;
        if(x==z||y==z||x+y==z) return true;
        return z%gcd(x,y)==0;
    }
    public int gcd(int a,int b)
    {
        if(b==0) return a;
        else return gcd(b,a%b);
    }
}

Reference

[1] https://github.com/EdwardShi92/Leetcode-Solution-Code/blob/master/WaterandJugProblem.java

[2] https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity#Generalizations

Leave a Reply

Your email address will not be published. Required fields are marked *