Polynomial Evaluator

Evaluate a polynomial expression at a given value of x using recursion

  1. // ==UserScript==
  2. // @name Polynomial Evaluator
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description Evaluate a polynomial expression at a given value of x using recursion
  6. // @match *://*/*
  7. // @grant none
  8. // @license MIT
  9. // ==/UserScript==
  10.  
  11. (function() {
  12. 'use strict';
  13.  
  14. // Function to evaluate a polynomial at a given value of x
  15. function evaluatePolynomial(coefficients, x, n) {
  16. // Base case: if n is 0, return the constant term
  17. if (n === 0) {
  18. return coefficients[0];
  19. }
  20. // Recursive case: compute the polynomial value
  21. return coefficients[n] * Math.pow(x, n) + evaluatePolynomial(coefficients, x, n - 1);
  22. }
  23.  
  24. // Example coefficients for P(x) = 2x^3 + 3x^2 + 4x + 5
  25. let coefficients = [5, 4, 3, 2]; // Coefficients are in increasing order of power
  26.  
  27. // Value of x at which to evaluate the polynomial
  28. let x = 2;
  29.  
  30. // Degree of the polynomial (highest power)
  31. let n = coefficients.length - 1;
  32.  
  33. // Evaluate the polynomial
  34. let result = evaluatePolynomial(coefficients, x, n);
  35.  
  36. console.log(`The value of the polynomial at x = ${x} is: ${result}`);
  37. })();