Java: 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:
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?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/math/java-math-exercise-23.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics