PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#GL0000067. Điện trở hữu tỉ tối thiểu (Rational Resistance)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Điện trở hữu tỉ tối thiểu (Rational Resistance)

Rational Resistance

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You have unlimited unit resistors of resistance 1. Starting with a single resistor, repeatedly add a unit resistor in series (new resistance R+1) or in parallel (new resistance R/(R+1)). Given a positive reduced fraction a/b, find the minimum number of unit resistors required to obtain exactly this resistance.

Input

Two positive coprime integers a b.

Output

The minimum number of resistors.

Subtasks

  • Subtask 1 (20 points): 1≤a,b≤301\le a,b\le 30; gcd⁡(a,b)=1\gcd(a,b)=1.
  • Subtask 2 (30 points): 1≤a,b≤1061\le a,b\le 10^6; gcd⁡(a,b)=1\gcd(a,b)=1.
  • Subtask 3 (50 points): 1≤a,b≤10181\le a,b\le 10^{18}; gcd⁡(a,b)=1\gcd(a,b)=1.

Examples

Input

3 2

Output

3

Explanation

Two resistors in parallel give 1/2; one further resistor in series gives 3/2, using three total.