Least Operators to Express Number in C++

C++Server Side ProgrammingProgramming

Suppose we have a positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where op1, op2, etc. are the operators. And these operators can be either addition, subtraction, multiplication, or division. For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3. There are few some rules, these are as follows -

  • The division operator (/) returns rational numbers.

  • There are no parentheses placed anywhere.

  • We use the usual order of operations − multiplication and division has higher priority than addition and subtraction.

  • Unary negation operator is not allowed.

We have to write an expression with the least number of operators such that the expression equals the given target. So, we will find the least number of operators.

So, if the input is like x = 4, target = 15, then the output will be 3, as we can express 15 as 4*4- 4/4

To solve this, we will follow these steps −

  • if target is same as x, then −

    • if x > target, then −

      • return minimum of (x - target) * 2 and (target * 2) - 1

  • sum := x, t := 0

  • while sum < target, do −

    • sum := sum * x

    • (increase t by 1)

  • if sum is same as target, then −

    • return t

  • l := inf, r := inf

  • if sum - target target, then −

    • r := leastOpsExpressTarget(x, sum - target)

  • l := leastOpsExpressTarget(x, target - (sum / x))

  • return 1 + minimum of l and r

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
   public:
   int leastOpsExpressTarget(int x, int target) {
      if(target == x) return 0;
      if(x > target){
         return min((x - target) * 2, (target * 2) - 1);
      }
      lli sum = x;
      int t = 0;
      while(sum < target){
         sum *= x;
         t++;
      }
      if(sum == target) return t;
      int l = INT_MAX;
      int r = INT_MAX;
      if(sum - target < target){
         r = leastOpsExpressTarget(x, sum - target) + t;
      }
      l = leastOpsExpressTarget(x, target - (sum / x)) + t - 1;
      return min(l, r) + 1;
   }
};
main(){
   Solution ob;
   cout << (ob.leastOpsExpressTarget(4, 15));
}

Input

4, 15

Output

3
raja
Published on 04-Jun-2020 13:06:18
Advertisements