Get reverse of an equation – JavaScript

• A+
Category：Languages

Let's say I have this formula, for example:

function getExperience(level) {   let a = 0;   for (let x = 1; x < level; x += 1) {     a += Math.floor(x + (200 * (2 ** (x / 3))));   }    return Math.floor(a / 4); }   for (var i = 1; i < 100; i++) {   console.log(`Level \${i}: \${getExperience(i)}`); }

To get the experience needed for level 50, you'd do: getExperience(50).

But, how would you reverse that and get the LEVEL needed for experience? So, getLevel(20010272) would output 50.

A brute-force (but inelegant) solution would be to just call getExperience for levels until you reach a level that requires more experience than the passed exp:

function getLevel(exp) {   let level = 0;   let calcExp = 0;   while (exp > calcExp) {     calcExp = getExperience(level);     if (calcExp >= exp) break;     level++;   }   return level; }  console.log(getLevel(20012272)); // experience required for 50 on the dot console.log(getLevel(20012270)); console.log(getLevel(20012274));  function getExperience(level) {   let a = 0;   for (let x = 1; x < level; x += 1) {     a += Math.floor(x + (200 * (2 ** (x / 3))));   }    return Math.floor(a / 4); }