题意:
开始他有一个数字n,他的目标是把它转换成m,在每一步操作中,他可以将n乘以2或乘以3,他可以进行任意次操作。输出将n转换成m的操作次数,如果转换不了输出-1。
输入:
输入的唯一一行包括两个整数n和m(1<=n<=m<=5*10^8).
输出:
输出从n转换到m的操作次数,否则输出-1.
输入、输出样例:
Simple Input 1
120 51840
Simple Output 1
7
Simple Input 2
42 42
Simple Output 2
0
Simple Input 3
48 72
Simple Output 3
-1
解题思路:
非常简单的题目,抓住b/a,若不能整除,直接输出-1,若能整除,一次次除以2再一次次除以3直到不能整除为止,这个过程中记录ans,若最后为1,则输出ans,否则表示不能转换,输出-1.
参考代码:
#include <iostream>
using namespace std;
int a,b;
int ans=0;
int main(int argc, const char * argv[]) {
cin>>a>>b;
if(b%a==0){
int x=b/a;
while (x%2==0) {
x/=2;
ans++;
}
while (x%3==0) {
x/=3;
ans++;
}
if(x==1)cout<<ans<<endl;
else cout<<-1<<endl;
}
else cout<<-1<<endl;
return 0;
}