The question asks if we can reach a number n from a number m by multiplying n by either 2 or 3
We can think of the problem as a path finding operation from the number n and m.
We can do that using recursion so we calculate all paths and we return the max of the solutions.
#include <bits/stdc++.h>
using namespace std;
int solve(int n, int m, int moves = 0)
{
if (n > m) {
return -1;
}
if (n == m) {
return moves;
}
// solve for n * 2
int n2 = solve(n * 2, m, moves + 1);
// solve for n * 3
int n3 = solve(n * 3, m, moves + 1);
return max(n2, n3);
}
int main()
{
int n, m;
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n >> m;
cout << solve(n, m) << "\n";
return 0;
}