×

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be many expressions that can bring out the target number but the expression with least or the minimum operators need to be found.

We must construct an equation or formula that comprises only the digit D and that evaluates to the number N given an integer N and the digit D. The operators +, -, *, or / may be used in expressions. Find the least number of operators that satisfy the requirement that D only exist in the expression 10(limit) times or less. Limit the N values as a result. Although how much further you want to go determines the value of limit. However, the below approach may take longer if the limit is large. Keep in mind that there may be more than just one minimal expression of D that equals N, however the expression with fewest operators must be chosen.

Let us understand more clearly with the examples.

Example 1

 N = 7, D = 3

 3/3+ 3 + 3

Interpretation: 3/3 = 1, and 1+3+3 = 7

The least operators required are 3.

Example 2

N = 501, D = 5

Interpretation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5.

The least operators required are 8.

Example 3

N = 7, D =4

Interpretation: (4+4+4)/4 +4

The least operators required are 4.

Let us understand it with a program.

File name : Solution.java

class Solution {
    Map<Integer, Integer> memo = new HashMap<>();
    public int leastOpsExpressTarget(int x, int target) {
        if (target == 1) 
            return x == 1 ? 0 : 1;
        if (memo.containsKey(target))
            return memo.get(target);
        long product = x;
        int count = 0;
        while (product < target) {
            count++;
            product *= x;
            
        }
        
        // candidate1 : in the form : x*x*...*x - (......) = target
        int cand1 = Integer.MAX_VALUE;
        if (product == target)
            cand1 = count;
        else if (product - target < target)
            cand1 = count + leastOpsExpressTarget(x, (int)(product - target)) + 1;
        
        // candidate2 : in the form : x*x*...*x + (......) = target
        int cand2 = Integer.MAX_VALUE;
        product /= x;
        cand2 = leastOpsExpressTarget(x, (int)(target - product)) + (count == 0 ? 2 : count);
        int res = Math.min(cand1, cand2);
        memo.put(target, res);
        return res;
    }
}

The above is the approach or the algorithm in Java, that can obtain the least count of operators as output.

Input

N = 501, D =5

Output

The expression contains 8 operations.

Input

N = 19, D = 3

Output

The expression contains 5 operations.

The Approach

Divided by (/), rational numbers are returned. There isn’t any parenthesis anywhere in the text. We follow the standard order of operations, with addition and subtraction coming after multiplication and division. Use of the unary negation operator is prohibited (-). For instance, "-x + x" is not a valid expression since it involves negation, but "x - x" is because it just uses subtraction. In order to create an expression that equals the specified target, we want to use the fewest possible operators. Give the least number of operators.

We employ a backtracking strategy. Starting with the provided Digit D, we multiply, add, subtract, add, and divide as much as we can. This method is continued until the sum equals N or until we arrive at the conclusion and turn around to begin a new path. We locate the recursive tree's lowest level in order to determine the smallest expression. utilize the backtracking algorithm after that. Then the program makes the count of the number of operators employed to bring out the desired output.

Note: If there exist expressions with same number of operators in them, anyone will be chosen among them. Both the expressions are valid.

Every level has four additional recursions (at-most). We may therefore claim that the approach has a temporal complexity of 4n, where n represents the number of levels in the recursion trees. Alternatively, we can specify the maximum number of times D should appear in the expression, in this example 10, which is ten.


Related Topics

Java Integer getInteger() method

The getInteger() method of Integer class determines the integer value of the system property with the given name. Syntax` public static Integer getInteger(String nm) Parameters The parameter ‘nm’ represents the property name. Throws The getInteger ()...

1 minute read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue...

4 minutes read.

Check the presence of Substring in a String in java

In java, the string can be treated as class and datatype. The string contains words and numbers but should be in double-quotes. Example: ” Omsairam” Substring The part of the string is called...

2 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Java Boolean logicalXor() Method

The logicalXor() method of Java Boolean class returns the result of implementing logical XOR operation on the specified Boolean operands. Syntax: public static boolean logicalXor (boolean a, boolean b) Parameters: The parameters ‘a’ and...

2 minutes read.

Tetris Game in Java

The Tetris game is among the most well-known video games ever produced for computers. Today, we may engage in this game on a mobile device as well. Alexey Pajitnov conceptualized...

12 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Java program to count the occurrences of each character

The count of each character is the frequency of the characters. For example, the given String is “Programming”. In the given string, the count of the characters ‘P’ -1, ’r’-2,...

6 minutes read.

Interface Program in Java

Interface Program in Java In the previous topic, we discussed that abstraction is possible through the interface and abstract class. An abstract class provides partial to 100% abstraction. 100 %abstraction in...

4 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Difference between final, finally, and finalize()

Difference between final, finally, and finalize() In Java, final, finally and finalize sound similar they are totally different in functionality. Final and finally are the two keywords but the finalize is...

4 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Java Speech Recognition

The customer experience and convenience are improved with its utilization. Command and control interest in buying and voice synthesizers are supported by the cross-platform API defined by the API. For...

4 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

How to Convert Object to String in Java

How to Convert Object to String in Java You can convert any Object to String in Java whether it is a user-defined class, StringBuilder or StringBuffer, etc. There are two methods...

2 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.