w3resource

Java Math Exercises: Compute the result from the innermost brackets

Java Math Exercises: Exercise-23 with Solution

A fast scheme for evaluating a polynomial such as:
-19+ 7x- 4x2 + 6x3
when
x=3
is to arrange the computation as follows:((((0)x+6)x+(-4))x+7)x+(-19)
Write a Java program to compute the result from the innermost brackets.

Sample Solution:

Java Code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class solution {
   public static void main(String[] args){
       List<Double> coeffs = new ArrayList<Double>();
       coeffs.add(-19.0);
       coeffs.add(7.0);
       coeffs.add(-4.0);
       coeffs.add(6.0);
       System.out.println(polyEval(coeffs, 3));
   }
   public static double polyEval(List<Double> coefficients, double x) {
       Collections.reverse(coefficients);
       Double accumulator = coefficients.get(0);
       for (int i = 1; i < coefficients.size(); i++) {
           accumulator = (accumulator * x) + (Double) coefficients.get(i);
       }
       return accumulator;
   }
}

Ref.: https://bit.ly/3chhDot

Sample Output:

128.0

Flowchart:

Flowchart: Compute the result from the innermost brackets.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to find next smallest palindrome.
Next: Write a Java program to calculate the Binomial Coefficient of two positive numbers.

What is the difficulty level of this exercise?



Java: Tips of the Day

Java: Create ArrayList from array

new ArrayList<>(Arrays.asList(array));

Ref: https://bit.ly/3a0wfum