js实现超大数字的加减乘除

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_41827547/article/details/89487456

网上没发现超大数字运算的js实现,标题有,但是并不是真正的超大数运算,而且有很多乘法加法都不精确的拿出来坑人。我自己实现了一版,性能还不错,支持数百万长度的精确数字运算,测试乘法10万长度在1分钟内完成,加法百万长度在一分钟内。除法和乘法互相验证没问题。

原理和我们手算差不多,只不过我把它分块了,不是逐位运算,而是逐块,性能也就提高了很多。

代码如下

// 不可使用负数

function compare(p, q) {
  while (p[0] === '0') {
    p = p.substr(1);
  }
  while (q[0] === '0') {
    q = q.substr(1);
  }
  if (p.length > q.length) {
    return 1;
  } else if (p.length < q.length) {
    return -1;
  } else {
    let i = 0;
    let a, b;
    while (1) {
      a = parseInt(p.charAt(i));
      b = parseInt(q.charAt(i));
      if (a > b) {
        return 1;
      } else if (a < b) {
        return -1;
      } else if (i === p.length - 1) {
        return 0;
      }
      i++;
    }
  }
}

function divide(A, B) {
  let result = [];
  let max = 9;
  let point = 5;
  let fill = 0;
  if (B.length - A.length > 0) {
    point += fill = B.length - A.length;
  }
  for (let i = 0; i < point; i++) {
    A += '0';
  }
  let la = A.length;
  let lb = B.length;

  let b0 = parseInt(B.charAt(0));
  let Adb = A.substr(0, lb);
  A = A.substr(lb);
  let temp, r;
  for (let j = 0; j < la - lb + 1; j++) {
    while (Adb[0] === '0') {
      Adb = Adb.substr(1);
    }
    if (Adb.length === lb) {
      max = Math.ceil((parseInt(Adb.charAt(0)) + 1) / b0); // 不可能取到这个最大值,1<= max <= 10
    } else if (Adb.length > lb) {
      max = Math.ceil((parseInt(Adb.substr(0, 2)) + 1) / b0);
    } else {
      result.push(0);
      Adb += A[0];
      A = A.substr(1);
      continue;
    }
    for (let i = max - 1; i >= 0; i--) {
      if (i === 0) {
        result.push(0);
        Adb += A[0];
        A = A.substr(1);
        break;
      } else {
        temp = temp || multiply(B, i + '');
        r = compare(temp, Adb);
        if (r === 0 || r === -1) {
          result.push(i);
          if (r) {
            Adb = reduce(Adb, temp);
            Adb += A[0];
          } else {
            Adb = A[0];
          }
          A = A.substr(1);
          break;
        } else {
          temp = reduce(temp, B);
        }
      }
    }
    temp = 0;
  }
  for (let i = 0; i < fill; i++) {
    result.unshift('0');
  }
  result.splice(result.length - point, 0, '.');

  if (!result[0] && result[1] !== '.') {
    result.shift();
  }

  point = false;
  let position = result.indexOf('.');

  for (let i = position + 1; i < result.length; i++) {
    if (result[i]) {
      point = true;
      break;
    }
  }
  if (!point) {
    result.splice(position);
  }

  result = result.join('');
  return result;
}

function multiply(A, B) {
  let result = [];
  (A += ''), (B += '');
  const l = -4; // 以支持百万位精确运算,但速度减半

  let r1 = [],
    r2 = [];
  while (A !== '') {
    r1.unshift(parseInt(A.substr(l)));
    A = A.slice(0, l);
  }
  while (B !== '') {
    r2.unshift(parseInt(B.substr(l)));
    B = B.slice(0, l);
  }
  let index, value;
  for (let i = 0; i < r1.length; i++) {
    for (let j = 0; j < r2.length; j++) {
      value = 0;
      if (r1[i] && r2[j]) {
        value = r1[i] * r2[j];
      }
      index = i + j;
      if (result[index]) {
        result[index] += value;
      } else {
        result[index] = value;
      }
    }
  }
  for (let i = result.length - 1; i > 0; i--) {
    result[i] += '';
    if (result[i].length > -l) {
      result[i - 1] += parseInt(result[i].slice(0, l));
      result[i] = result[i].substr(l);
    }
    while (result[i].length < -l) {
      result[i] = '0' + result[i];
    }
  }
  if (result[0]) {
    result = result.join('');
  } else {
    result = '0';
  }
  return result;
}

function add(A, B) {
  let result = [];
  (A += ''), (B += '');
  const l = -15;
  while (A !== '' && B !== '') {
    result.unshift(parseInt(A.substr(l)) + parseInt(B.substr(l)));
    A = A.slice(0, l);
    B = B.slice(0, l);
  }
  A += B;

  for (let i = result.length - 1; i > 0; i--) {
    result[i] += '';
    if (result[i].length > -l) {
      result[i - 1] += 1;
      result[i] = result[i].substr(1);
    } else {
      while (result[i].length < -l) {
        result[i] = '0' + result[i];
      }
    }
  }

  while (A && (result[0] + '').length > -l) {
    result[0] = (result[0] + '').substr(1);
    result.unshift(parseInt(A.substr(l)) + 1);
    A = A.slice(0, l);
  }

  if (A) {
    while ((result[0] + '').length < -l) {
      result[0] = '0' + result[0];
    }
    result.unshift(A);
  }

  if (result[0]) {
    result = result.join('');
  } else {
    result = '0';
  }

  return result;
}

function reduce(A, B) {
  let result = [];
  (A += ''), (B += '');
  while (A[0] === '0') {
    A = A.substr(1);
  }
  while (B[0] === '0') {
    B = B.substr(1);
  }
  const l = -15;
  let N = '1';
  for (let i = 0; i < -l; i++) {
    N += '0';
  }
  N = parseInt(N);
  while (A !== '' && B !== '') {
    result.unshift(parseInt(A.substr(l)) - parseInt(B.substr(l)));
    A = A.slice(0, l);
    B = B.slice(0, l);
  }
  if (A !== '' || B !== '') {
    let s = B === '' ? 1 : -1;
    A += B;
    while (A !== '') {
      result.unshift(s * parseInt(A.substr(l)));
      A = A.slice(0, l);
    }
  }
  while (result.length !== 0 && result[0] === 0) {
    result.shift();
  }
  let s = '';
  if (result.length === 0) {
    result = 0;
  } else if (result[0] < 0) {
    s = '-';
    for (let i = result.length - 1; i > 0; i--) {
      if (result[i] > 0) {
        result[i] -= N;
        result[i - 1]++;
      }
      result[i] *= -1;
      result[i] += '';
      while (result[i].length < -l) {
        result[i] = '0' + result[i];
      }
    }
    result[0] *= -1;
  } else {
    for (let i = result.length - 1; i > 0; i--) {
      if (result[i] < 0) {
        result[i] += N;
        result[i - 1]--;
      }
      result[i] += '';
      while (result[i].length < -l) {
        result[i] = '0' + result[i];
      }
    }
  }

  if (result) {
    while ((result[0] = parseInt(result[0])) === 0) {
      result.shift();
    }
    result = s + result.join('');
  }
  return result;
}

测试HTML文件可以用这个

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <style>
      textarea {
        display: block;
        width: 70%;
        height: 150px;
      }
      #stats {
        width: 100%;
        word-break: break-all;
      }
    </style>
  </head>
  <body>
    值1:
    <textarea></textarea>
    值二:
    <textarea></textarea>
    <button οnclick="handleAdd()">相加</button>
    <button οnclick="handleReduce()">相减</button>
    <button οnclick="handleMultiply()">相乘</button>
    <button οnclick="handleDivide()">相除</button>
    <div id="stats"></div>
    <script>
      const stats = document.getElementById('stats');
      function getValue() {
        let textarea = document.getElementsByTagName('textarea');
        return {
          x: textarea[0].value,
          y: textarea[1].value
        };
      }
      function handleAdd() {
        let { x, y } = getValue();
        let t0 = new Date().getTime();
        let value = add(x, y);
        let t1 = new Date().getTime();
        let t = t1 - t0;
        let isEqual = y === reduce(value, x);
        stats.innerHTML = `计算值:${value}<br/>耗时:${t}<br/>{计算值长度:${
          value.length
        }<br/>值一长度:${x.length}<br/>值二长度:${
          y.length
        }<br/>是否相等:${isEqual}`;
      }
      function handleReduce() {
        let { x, y } = getValue();
        let t0 = new Date().getTime();
        let value = reduce(x, y);
        let t1 = new Date().getTime();
        let t = t1 - t0;
        stats.innerHTML = `计算值:${value}<br/>耗时:${t}<br/>{计算值长度:${
          value.length
        }<br/>值一长度:${x.length}<br/>值二长度:${y.length}`;
      }
      function handleMultiply() {
        let { x, y } = getValue();
        let t0 = new Date().getTime();
        let value = multiply(x, y);
        let t1 = new Date().getTime();
        let t = t1 - t0;
        let isEqual = y === divide(value, x);
        stats.innerHTML = `计算值:${value}<br/>耗时:${t}<br/>{计算值长度:${
          value.length
        }<br/>值一长度:${x.length}<br/>值二长度:${
          y.length
        }<br/>是否相等:${isEqual}`;
      }

      function handleDivide() {
        let { x, y } = getValue();
        let t0 = new Date().getTime();
        let value = divide(x, y);
        let t1 = new Date().getTime();
        let t = t1 - t0;
        stats.innerHTML = `计算值:${value}<br/>耗时:${t}<br/>计算值长度:${
          value.length
        }<br/>值一长度:${x.length}<br/>值二长度:${y.length}`;
      }
    </script>
    <script src="./main.js"></script>
  </body>
</html>

 

 

 

 

展开阅读全文

[学习]超大数字的计算

05-26

记得有问过超大数字计算的问题,现给出代码供大家学习。rnrn'函数调用:rn'LargeAdd(数字1+数字2)rn'LargeSubtract(数字1-数字2)rn'LargeMultiply(数字1×数字2)rn'LargeDivide(数字1/数字2)rnrnrnrn'模块声明rn' Code returned by functions when error occursrnPrivate Const ErrorCode = "ERROR"rnrnPublic Function LargeAdd(ByVal Number1 As String, ByVal Number2 As String) As Stringrn ' Adds Number2 to Number1 and returns the result in a stringrn Dim TempDigit1 As Integer, TempDigit2 As Integerrn Dim CalcResult As Stringrn Dim AddBuffer As Integerrn rn If Not IsNumeric(Number1) Or Not IsNumeric(Number2) Thenrn LargeAdd = ErrorCodern Exit Functionrn End Ifrn rn ' Fill up the shorter number with zeroes at the beginning to make them equal in lengthrn If Len(Number1) > Len(Number2) Thenrn Number2 = String(Len(Number1) - Len(Number2), "0") & Number2rn ElseIf Len(Number1) < Len(Number2) Thenrn Number1 = String(Len(Number2) - Len(Number1), "0") & Number1rn End Ifrn rn ' Add one zero at the beginning of each number to make sure no digit gets lost when thern ' sum of two digits is greater than 10 (see below)rn Number1 = "0" & Number1rn Number2 = "0" & Number2rn rn For cCount = Len(Number1) To 1 Step -1rn ' Add the numbers digit by digit to one anotherrn TempDigit1 = CInt(Mid(Number1, cCount, 1))rn TempDigit2 = CInt(Mid(Number2, cCount, 1))rn rn If TempDigit1 + TempDigit2 + AddBuffer >= 10 Thenrn CalcResult = CStr(TempDigit1 + TempDigit2 + AddBuffer - 10) & CalcResultrn ' AddBuffer contains 1 if the sum of two digits is greater than 10rn AddBuffer = 1rn Elsern CalcResult = CStr(TempDigit1 + TempDigit2 + AddBuffer) & CalcResultrn AddBuffer = 0rn End Ifrn Next cCountrn rn If Left(CalcResult, 1) = "0" Then CalcResult = Mid(CalcResult, 2)rn LargeAdd = CalcResultrnEnd FunctionrnrnPublic Function LargeSubtract(ByVal Number1 As String, ByVal Number2 As String) As Stringrn ' Subtracts Number2 from Number1 and returns the result in a stringrn Dim TempBuffer As Stringrn Dim TempDigit1 As Integer, TempDigit2 As Integerrn Dim CalcResult As Stringrn Dim SubtractBuffer As Integerrn rn If Not IsNumeric(Number1) Or Not IsNumeric(Number2) Thenrn LargeSubtract = ErrorCodern Exit Functionrn End Ifrn rn ' If the numbers are equal, the result is zerorn If LargeCompare(Number1, Number2) = 0 Thenrn LargeSubtract = "0"rn Exit Functionrn End Ifrn rn ' Fill up the shorter number with zeroes at the beginning to make them equal in lengthrn If Len(Number1) > Len(Number2) Thenrn Number2 = String(Len(Number1) - Len(Number2), "0") & Number2rn ElseIf Len(Number1) < Len(Number2) Thenrn Number1 = String(Len(Number2) - Len(Number1), "0") & Number1rn End Ifrn rn ' Put the larger number in Number1 (otherwise digit-by-digit subtraction won't work)rn If LargeCompare(Number1, Number2) = 2 Thenrn TempBuffer = Number2rn Number2 = Number1rn Number1 = TempBufferrn End Ifrn rn For cCount = Len(Number1) To 1 Step -1rn ' Subtract the numbers digit by digit from one anotherrn TempDigit1 = CInt(Mid(Number1, cCount, 1))rn TempDigit2 = CInt(Mid(Number2, cCount, 1))rn rn If TempDigit1 - TempDigit2 - SubtractBuffer < 0 Thenrn CalcResult = CStr(TempDigit1 - TempDigit2 - SubtractBuffer + 10) & CalcResultrn ' SubtractBuffer contains 1 if Digit1 - Digit2 < 0rn SubtractBuffer = 1rn Elsern CalcResult = CStr(TempDigit1 - TempDigit2 - SubtractBuffer) & CalcResultrn SubtractBuffer = 0rn End Ifrn Next cCountrn rn If TempBuffer <> "" Then CalcResult = "-" & CalcResultrn LargeSubtract = CalcResultrnEnd FunctionrnrnPublic Function LargeMultiply(ByVal Number1 As String, ByVal Number2 As String) As Stringrn ' Multiplies Number1 with Number2 and returns the result in a stringrn Dim TempDigit1 As Integer, TempDigit2 As Integerrn Dim CalcResult As Stringrn rn If Not IsNumeric(Number1) Or Not IsNumeric(Number2) Thenrn LargeMultiply = ErrorCodern Exit Functionrn End Ifrn rn CalcResult = "0"rn rn For cCount = Len(Number1) To 1 Step -1rn For dCount = Len(Number2) To 1 Step -1rn TempDigit1 = CInt(Mid(Number1, cCount, 1))rn TempDigit2 = CInt(Mid(Number2, dCount, 1))rn rn ' Split the multiplication into additions:rn 'rn ' abc * def = 10^0 * cf + 10^1 * ce + 10^2 * cd +rn ' 10^1 * bf + 10^2 * be + 10^3 * bd +rn ' 10^2 * af + 10^3 * ae + 10^4 * adrn CalcResult = LargeAdd(CalcResult, CStr(TempDigit1 * TempDigit2) & _rn String((Len(Number1) - cCount) + (Len(Number2) - dCount), "0"))rn Next dCountrn Next cCountrn rn LargeMultiply = CalcResultrnEnd FunctionrnrnPublic Function LargeDivide(ByVal Number1 As String, ByVal Number2 As String) As Stringrn ' Divides Number1 by Number2 and returns the result in a stringrn If Not IsNumeric(Number1) Or Not IsNumeric(Number2) Thenrn LargeDivide = ErrorCodern Exit Functionrn End IfrnEnd FunctionrnrnrnrnPublic Function LargeCompare(ByVal Number1 As String, ByVal Number2 As String) As Integerrn ' Compares Number1 with Number2rn 'rn ' Returns 1 if Number1 is greater than Number2rn ' Returns 2 if Number2 is greater than Number1rn ' Returns 0 if the numbers are equalrn ' Returns -1 if an error occursrn rn If Not IsNumeric(Number1) Or Not IsNumeric(Number2) Thenrn LargeCompare = -1rn Exit Functionrn End Ifrn rn ' Test if one of the numbers is shorter than the other onern If Len(Number1) > Len(Number2) Thenrn LargeCompare = 1rn Exit Functionrn ElseIf Len(Number1) < Len(Number2) Thenrn LargeCompare = 2rn Exit Functionrn End Ifrn rn ' The numbers are equal in length => compare them digit by digitrn For cCount = 1 To Len(Number1)rn If CInt(Mid(Number1, cCount, 1)) > CInt(Mid(Number2, cCount, 1)) Thenrn LargeCompare = 1rn Exit Functionrn ElseIf CInt(Mid(Number1, cCount, 1)) < CInt(Mid(Number2, cCount, 1)) Thenrn LargeCompare = 2rn Exit Functionrn End Ifrn Next cCountrn rn LargeCompare = 0rnEnd Functionrnrnrnrn 论坛

没有更多推荐了,返回首页