Friday, July 01, 2011

No Overflow for a Simple Math Calculation

I watched WebBeat podcast one day in the last month. One video show got my attention: Explaining visual math in a simple way. I wrote a blog on my Chinese blog. It is very interesting to resolve a math multiply by visualization graphs. However, this method only applies to multiply of 2 digit numbers, and it becomes tedious when there carrier forward in the last and middle numbers.

This reminds me a long time puzzle problem: how to resolve overflow issue when the result of multiply of two integers is too big. I recall the traditional method of multiply algorithm and relate it to this visualization. Soon I realize that I could resolve the overflow issue by creating a small app. I gave it a try with Javascript and I got it worked out! I am very happy with the result. No more overflow no matter how big numbers they are!

Here is my Javascript function:

function v1timesv2(v1, v2) {
  var x = ''; // result
  var i = 0;
  var j = 0;
  var r;
  var r1;
  var r2;
  var k;
  var tempVal;
  var preTempVal = '';
  debug ('v1: ' + v1);
  debug ('v2: ' + v2);
  for (i= v2.length-1; i >= 0; i--) // v2
  {
    r2 = 0;
    tempVal = '';
    k = preTempVal.length;
    for (j=v1.length-1;j >=0; j--)  // v1
    {
      if ((k--) > 0)
      {
        r2 += Number(preTempVal[k]);
      }
      r = v1[j] * v2[i] + r2;
      r1 = r % 10;
      r2 = 0;
      if ( r > 9 )
      {
        r2 = (r - r1) / 10;
      }
      tempVal = r1 + tempVal;
    }
    if ( r > 9 )
    {
       tempVal = r2 + tempVal;
    }
    debug('intermediate calculated result: ' + tempVal);
    // Get the last char as result
    x = tempVal[tempVal.length - 1] + x;
    debug('intermediate result: ' + x);
    // Get the remaining as previous val
    if ( tempVal.length > 1 )
    {
      preTempVal = tempVal.substr(0, tempVal.length - 1);
    }
    else
    {
      preTempVal= '';
    }
    debug('== carry forward result: ' + preTempVal + ' ==' );
  }
  x = preTempVal + x;
  debug('>>final result:    ' + x);
  debug('>>verified result: ' + Number(v1) * Number(v2) + ' (' + v1 + ' x ' + v2 + ')');
  return x ;
}


This may not be the best codes. Please let me know if you can simplify my codes. Download my numberCalc.html and drop it to a browser. I challenge if you can break my codes with an overflow!


References


0 comments: