Least Operators to Express Number - Problem

Given a single positive integer x, we will write an expression of the form x (op1) x (op2) x (op3) x ... where each operator op1, op2, etc. is either addition, subtraction, multiplication, or division (+, -, *, or /).

For example, with x = 3, we might write 3 * 3 / 3 + 3 - 3 which is a value of 3.

When writing such an expression, we adhere to the following conventions:

  • The division operator (/) returns rational numbers.
  • There are no parentheses placed anywhere.
  • We use the usual order of operations: multiplication and division happen before addition and subtraction.
  • It is not allowed to use the unary negation operator (-). For example, x - x is a valid expression as it only uses subtraction, but -x + x is not because it uses negation.

We would like to write an expression with the least number of operators such that the expression equals the given target. Return the least number of operators used.

Input & Output

Example 1 — Small Target
$ Input: x = 3, target = 19
Output: 5
💡 Note: We can write 19 as 3*3*3 - 3 - 3 - 3 + 3/3, which uses 5 operators: 3 multiplications + 2 subtractions = 5 total operators
Example 2 — Simple Case
$ Input: x = 5, target = 501
Output: 8
💡 Note: 501 can be expressed as 5*5*5*4 + 1, where 4 = 5-1 and 1 = 5/5, requiring 8 operators total
Example 3 — Edge Case
$ Input: x = 100, target = 100
Output: 1
💡 Note: Target equals x, so we just need 1 occurrence of x with 0 operators between

Constraints

  • 2 ≤ x ≤ 100
  • 1 ≤ target ≤ 2 × 108

Visualization

Tap to expand
Least Operators Problem: x=3, target=19Inputx = 3, target = 19Expression3*3*3 - 3 - 3 - 3 + 3/3Output5 operators3*3*3 = 2727-9 = 1818+1 = 19Where 1 = 3/3Count operators: 2(*) + 2(-) + 1(/) = 5 totalChallenge: Find the minimum operators neededStrategy: Use mathematical properties of powers
Understanding the Visualization
1
Input
Given x=3 and target=19, find minimum operators
2
Process
Express 19 using powers of 3 with +, -, *, / operators
3
Output
Return minimum operators needed: 5
Key Takeaway
🎯 Key Insight: Express the target as a combination of powers of x, choosing between positive and negative contributions to minimize total operators
Asked in
Google 15 Facebook 12 Microsoft 8
28.0K Views
Medium Frequency
~35 min Avg. Time
845 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen