Under construction

Still being built. Things may change

Espresso Made Your Way

Time limit1sMemory limit1024 MB

Summary
Given a customer's accepted range of coffee-to-milk ratios, find the fewest cups of ingredients that must be wasted when mixing half-full cups of pure coffee and pure milk to hit some ratio in that range.
Level

Medium7 of 10

Topics
Stack, Greedy, Math, Number theory
Solved
No attempts yet

Problem

You have a new job. Coffee is not your cup of tea. Many customers ask for a particular ratio of coffee to milk. You cannot make arbitrary measurements. You have two cups of the same size, a machine that dispenses pure coffee, and another machine that dispenses pure milk.

You can completely fill one empty cup with coffee and the second empty cup with milk. You can also take these two full cups and mix them so that the result has exactly half of each cup, that is, half coffee and half milk. This gives you a cup that is half coffee and half milk, but you have wasted a full cup of ingredients (the second half of the coffee and the second half of the milk).

Now that you have a cup that is half coffee and half milk, you can fill the second cup with coffee or fill it with milk. Then you can mix the two cups to create a cup with a different ratio. When mixing two cups, you use exactly half of each cup and waste exactly half of each cup.

By repeating this process, you can make some coffee-to-milk ratios, but some ratios are impossible.

Given the range of coffee-to-milk ratios a customer accepts, determine the least amount of ingredients you will waste when you prepare the order optimally.

Input

There is one input line containing four integers C1C_1, M1M_1, C2C_2, and M2M_2 (0≤C1,M1,C2,M2≤1060 \le C_1, M_1, C_2, M_2 \le 10^6). The customer accepts any ratio from C1C_1 parts coffee per M1M_1 parts milk to C2C_2 parts coffee per M2M_2 parts milk. The two ratios are not identical, C1+M1>0C_1 + M_1 > 0, C2+M2>0C_2 + M_2 > 0, and C1C1+M1≠C2C2+M2\frac{C_1}{C_1+M_1} \ne \frac{C_2}{C_2+M_2}.

Output

Print one integer: the least number of cups of ingredients wasted when the order is prepared optimally.

Examples3

  1. Example 1

    Input
    1 2 2 1
    
    Expected output
    1
    
  2. Example 2

    Input
    1 10 0 1
    
    Expected output
    0
    
  3. Example 3

    Input
    1 99 49 51
    
    Expected output
    2