Simple equation on Javascript not working and I can't see the problem

I’m trying to solve a simple equation "2^x=y" in javascript, but I can’t see what’s wrong with it, the browser just seems to enter an infinite loop… Here’s the code:

Edit: I changed the code to the whole script so you guys can see, the function that does the equation is the last one. Also apparently I have to talk more in order to edit the post sorry 🙂

var x = 0;
var y = 0;

function SolveEquation(input){
    while(x < input){
        x = Math.pow(2, y);
        y = y+1;
    if(x >= input){
        return x;

26 thoughts on “Simple equation on Javascript not working and I can't see the problem”

  1. several things seem to be wrong with this code.

    1. Never use global variables. pass x & y into your function

    2. this is supposed to be a function but its possible for undefined to be returned, which is bad coding for a function. (your only return statement is contained in an if statement)

    3. depending on the values of x and "input" its very possible you will never exit the while statement. again bad coding. maybe check that the values are valid, or re-write the function so it always works no matter what values are passed in.

  2. I feel like your problem isn’t so much Javascript as it your algebra.

    Assuming input is y and you’re solving for x, it’s:

    • 2^x = y
    • log2(2^x) = log2(y)
    • x * log2(2) = log2(y)
    • x * 1 = log2(y)
    • x = log2(y)
    function SolveEquation(input) {
      return Math.log2(input);

Leave a Comment