問題一覧 > 通常問題

No.141 Magical Girl Koba

レベル : / 実行時間制限 : 1ケース 5.000秒 / メモリ制限 : 512 MB / 標準ジャッジ問題
タグ : (AC するまで非表示) / 解いたユーザー数 268
作問者 : koba-e964
お気に入りにしたユーザー ProblemId : 228 / 自分の提出
問題文最終更新日: 2026-06-26 23:02:44
This statement was translated by AI (claude-opus-5-5, effort medium) and may contain errors or differ in nuance from the original. The original statement takes precedence. Back to the original
yukicoder contest 82 (順位表) の他の問題:

Problem Statement

Koba, a magical girl, has learned magic that changes numbers. Koba can use the following two types of magic:
(1) Add $1$ to a number $a$, changing it to $a+1$.
(2) When a number $a$ is not $0$, change $a$ to its reciprocal $1/a$.
Starting from the number $1$ and repeatedly changing it with magic, output the minimum number of magic uses required to reach the given number $M/N$. If $M/N$ cannot be obtained no matter how $1$ is changed, output $-1$.
$M$ and $N$ are not necessarily coprime; if they are not coprime, it suffices to change the number into the reduced fraction of $M/N$. For example, if $M = 4, N = 6$, output the minimum number of uses required to change it into 2/3.

Input

The input is given in the following format.
M N 

Here, $M,N$ are integers satisfying $1 \le M,N \le 10^9$.

Output

Output the minimum number of magic uses required to change $1$ into $M/N$. If $M/N$ cannot be reached regardless of the order in which magic is used, output $-1$. Print a newline at the end.

Sample

Sample 1
Input
2 3
Output
4

Using magic in the order (1),(2),(1),(2) gives 1 → 2 → 1/2 → 3/2 → 2/3, which yields 2/3. There is no way to obtain 2/3 with 3 or fewer uses of magic, so this is the minimum.

Sample 2
Input
10 7
Output
7


Using magic in the order (1),(1),(2),(1),(1),(2),(1) gives 1 → 2 → 3 → 1/3 → 4/3 → 7/3 → 3/7 → 10/7, which yields 10/7.

Sample 3
Input
1000000000 999999999
Output
1000000000

Sample 4
Input
4 6
Output
4


$M, N$ are not necessarily coprime.

Note

Among the test cases, those whose file names begin with "testcase-small-" satisfy $1 \le M,N \le 300$.

提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。