There are three integers k,m,n. You have to convert the number k to m by performing the given operations:
- Multiply k by n
- Decrease k by 2.
- Decrease k by 1.
You have to perform the above operations to convert the integer from k to m and find the minimum steps.
Example:
Input: k=3, m=10, n=2
Output: 3
Approach
Java
public class MinimumSteps {public static void main(String args[]) {int k = 3;int m = 10;int n = 2;System.out.println(rec(k, m, n));}public static int rec(int k, int m, int n) {if (k >= m)return (k - m) / 2 + (k - m) % 2;if (m % n == 0)return 1 + rec(k, m / n, n);int x = (m / n + 1) * n;return (x - m) / 2 + (x - m) % 2 + rec(k, x, n);}}
No comments:
Post a Comment