343A.md (2331B)
1 Source: https://codeforces.com/problemset/problem/343/A 2 3 A. Rational Resistance 4 5 time limit per test 6 7 1 second 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 stdin 16 17 output 18 19 stdout 20 21 Mad scientist Mike is building a time machine in his spare time. To finish the work, he needs a resistor with a certain resistance value. 22 23 However, all Mike has is lots of identical resistors with unit resistance *R*0 = 1. Elements with other resistance can be constructed from these resistors. In this problem, we will consider the following as elements: 24 25 1. one resistor; 26 2. an element and one resistor plugged in sequence; 27 3. an element and one resistor plugged in parallel. 28 29  30 31 With the consecutive connection the resistance of the new element equals *R* = *R**e* + *R*0. With the parallel connection the resistance of the new element equals . In this case *R**e* equals the resistance of the element being connected. 32 33 Mike needs to assemble an element with a resistance equal to the fraction . Determine the smallest possible number of resistors he needs to make such an element. 34 35 Input 36 37 The single input line contains two space-separated integers *a* and *b* (1 ≤ *a*, *b* ≤ 1018). It is guaranteed that the fraction  is irreducible. It is guaranteed that a solution always exists. 38 39 Output 40 41 Print a single number — the answer to the problem. 42 43 Please do not use the %lld specifier to read or write 64-bit integers in С++. It is recommended to use the cin, cout streams or the %I64d specifier. 44 45 Examples 46 47 Input 48 49 ``` 50 1 1 51 ``` 52 53 Output 54 55 ``` 56 1 57 ``` 58 59 Input 60 61 ``` 62 3 2 63 ``` 64 65 Output 66 67 ``` 68 3 69 ``` 70 71 Input 72 73 ``` 74 199 200 75 ``` 76 77 Output 78 79 ``` 80 200 81 ``` 82 83 Note 84 85 In the first sample, one resistor is enough. 86 87 In the second sample one can connect the resistors in parallel, take the resulting element and connect it to a third resistor consecutively. Then, we get an element with resistance . We cannot make this element using two resistors.