-1

I'trying to make a function creates a list of exponentially increasing numbers where the sum of the numbers is equal to some maximum.

For example:

/*
* What do I have to raise N by in order for the sum to be 40
*/

(1**x + 2**x + 3**x + 4**x + 5**x) === 40;

/*
* Wolframalpha tells me: x = 1.76445
* But how can I solve with JS.
*/ 
function listOfNumbers(n, maxSum) {
  // implementation
}

var result = listOfNumbers(5, 40);
/*
 * result === [1, 3.397..., 6.947..., 11.542...,  17.111...]
 * 
*/

result.reduce((acc, n) => acc += n) === 40
J. Wester
  • 3
  • 1
  • The question reads as incomplete. You should indicate in the post what your current code is doing or isn't doing. For example is it working at all, or partially, if so what are you getting as a result? Can you create the example in JS fiddle? – Jeff Mergler Jun 14 '19 at 21:08
  • Welcome to StackOverflow. Unfortunately, I'm not sure this question is a good fit for the site. Generally speaking, SO is a site for specific questions about programming. What we have in your question is you are essentially asking the community to write complete code for you in `// implementation`. I'd recommend reviewing [ask], trying a bit more yourself, and returning with a more complete question if you still need help. Good luck, and happy coding! – Alexander Nied Jun 14 '19 at 21:09
  • Also worth noting-- you're going to have to manage [floating point precision in JavaScript](https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) for this problem. – Alexander Nied Jun 14 '19 at 21:14
  • 1
    You don't solve this with JavaScript, you solve it with maths. Once you found a viable approach, you can implement that in JS. – Bergi Jun 14 '19 at 21:31
  • 1
    This may be a good place to ask for the mathematical formula to use: https://math.stackexchange.com/. Once you have the formula, the Javascript should be more straightforward. – cybersam Jun 14 '19 at 21:33
  • @cybersam I feel however that there is no symbolic solution and you need to do a numerical approximation anyway. – Bergi Jun 14 '19 at 21:52

1 Answers1

0

try https://en.wikipedia.org/wiki/Bisection_method

TOLERANCE = 1e-5;

let f = x => (1 ** x + 2 ** x + 3 ** x + 4 ** x + 5 ** x - 40);

let
    min = 0,
    max = 1,
    x = 0;

// roughly locate the upper bound

while (f(max) < 0)
    max *= 2;

// repeatedly bisect the interval [min, max]

while (1) {
    x = (min + max) / 2;
    let r = f(x);

    if (Math.abs(r) < TOLERANCE)
        break;

    if (r > 0) {
        max = x
    } else {
        min = x
    }
}

// now, x is a "good enough" approximation of the root

console.log(x);
georg
  • 211,518
  • 52
  • 313
  • 390