Friday, October 7, 2022
HomeSoftware DevelopmentConvert N to Ok by multiplying by A or B in minimal...

# Convert N to Ok by multiplying by A or B in minimal steps

Given two numbers N and Ok, and a pair A and B, the duty is to multiply N by A or B as many instances to get Ok in minimal steps. If it isn’t attainable to acquire Ok from N, return -1;

Examples:

Enter: n = 4, okay = 5184, a = 2, b = 3
Output: 8
Rationalization: 4→12→24→72→144→432→1296→2592→5184

Enter: n = 5, okay = 13, a = 2, b = 3
Output: -1

Method: The given downside might be solved by utilizing recursion.

Comply with the steps to resolve this downside:

• Initialize a depend variable, Cnt = 0.
• Name a recursive operate to resolve with a parameter n, okay, a, b, Cnt.
• Examine, if n == okay, return Cnt.
• Else if, n > okay, return INT_MAX;
• Name, min(remedy(a*n, okay, a, b, Cnt + 1), remedy(b*n, okay, a, b, Cnt + 1)).
• If, the return worth will not be equal to INT_MAX then print it else print -1.

Beneath is the implementation of the above strategy.

## C++

 `#embody ` `utilizing` `namespace` `std;` ` `  `int` `remedy(``int` `n, ``int``& okay, ``int``& a, ``int``& b, ``int` `Cnt)` `{` ` `  `    ``if` `(n == okay) {` `        ``return` `Cnt;` `    ``}` ` `  `    ``if` `(n > okay) {` `        ``return` `INT_MAX;` `    ``}` ` `  `    ``return` `min(remedy(a * n, okay, a, b, Cnt + 1),` `               ``remedy(b * n, okay, a, b, Cnt + 1));` `}` ` `  `int` `principal()` `{` ` `  `    ``int` `n = 4;` `    ``int` `okay = 5184;` ` `  `    ``int` `a = 2, b = 3;` ` `  `    ` `    ``int` `res = remedy(n, okay, a, b, 0);` ` `  `    ``if` `(res != INT_MAX)` `        ``cout << res << endl;` `    ``else` `        ``cout << -1 << endl;` ` `  `    ``return` `0;` `}`

Time Complexity: O(2^okay)
Auxiliary House: O(2^okay)

RELATED ARTICLES