Search code examples
javascriptmathfactoriallargenumber

Math crossing out


I am looking to play around with probability that involves a lot if big numbers. To save computing time, I was thinking about having the computer cross out terms like you do in regular math. For example:

(2*3*7*3) / (3*2*3*3)

Can be simplified to 7/3

If I were to create a Javascript function and pass it two arrays containing multiplication numbers to cross out, how would I go about doing this?

Just to be clear:

If I passed in [3, 4, 6, 4] and [4, 7, 3, 2], it would return two arrays: [4, 6] and [7, 2]


Solution

  • If you do not require cancellation beyond exact numbers, this should do:

    var x = [3, 4, 6, 4];
    var y = [4, 7, 3, 2];
    for(var i in x)
    {
      for(var j in y)
      {
        if(x[i]==y[j])
        {
          x.splice(i,1);
          y.splice(j,1);
        }
      }
    }
    console.log(x);
    console.log(y);
    

    But in case you are interested in further cancellation take this:

    var x = [3, 4, 6, 4];
    var y = [4, 7, 3, 2];
    for(var i in x)
    {
      for(var j in y)
      {
        if(x[i]%y[j] == 0)
        {
          if(x[i]/y[j] > 1)
          {
            x[i] = x[i]/y[j];
          }
          else{
            x.splice(i,1);
          }
          y.splice(j,1);
        }
      }
    }
    
    console.log(x);
    console.log(y);