#C++初学记录(算法2)

A - Game 23
Polycarp plays "Game 23". Initially he has a number n and his goal is to transform it to m. In one move, he can multiply n by 2 or multiply n by 3. He can perform any number of moves.

Print the number of moves needed to transform n to m. Print -1 if it is impossible to do so.

It is easy to prove that any way to transform n to m contains the same number of moves (i.e. number of moves doesn't depend on the way of transformation).
Input
The only line of the input contains two integers n and m (1≤n≤m≤5⋅108).

Output
Print the number of moves to transform n to m, or -1 if there is no solution.

Examples
Input
120 51840
Output
7
Input
42 42
Output
0
Input
48 72
Output
-1
Note
In the first example, the possible sequence of moves is: 120→240→720→1440→4320→12960→25920→51840. The are 7 steps in total.

In the second example, no moves are needed. Thus, the answer is 0.

In the third example, it is impossible to transform 48 to 72.

正确代码

#include<cstdio>
int res, num = 0,flag = 0, n, m;
void getRes(int n, int m)
{
    if(n == m)
    {
        res = num;
        flag = 1;
        return;
    }
    if(n > m)return;
    num++;
    getRes(n * 2, m);
    getRes(n * 3, m);
    num--;
}
int main()
{
    scanf("%d %d", &n, &m);
    getRes(n, m);
    if(flag)
    {
        printf("%d\n", res);
    }
    else
    {
        printf("-1\n");
    }
    return 0;
}

代码理解
解决这个问题首要想到的是使用递归函数进行运算,题目较为简单,但是实际解决时遇到问题导致不能AC,其一是因为受汉诺塔的影响使用递归时经常想要从后往前推,其实不然,递归问题由前往后推应该也是我们必须理解并使用的问题。这类题型就使用了递归问题由前向后推,由前向后推更容易理解,由后往前推也可以做出,使用变量num使之当做指示变量,进行几次递归则进行几次加一,递归使用后再进行相减得到原始变量防止运行程序出错。

posted @ 2019-04-14 19:38  十魇  阅读(114)  评论(0编辑  收藏  举报
GenerateContentList