You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.1 KiB

4 years ago
  1. 'use strict';
  2. function genCombMulTo (alen, blen) {
  3. var len = alen + blen - 1;
  4. var src = [
  5. 'var a = self.words;',
  6. 'var b = num.words;',
  7. 'var o = out.words;',
  8. 'var c = 0;',
  9. 'var lo;',
  10. 'var mid;',
  11. 'var hi;'
  12. ];
  13. for (var i = 0; i < alen; i++) {
  14. src.push('var a' + i + ' = a[' + i + '] | 0;');
  15. src.push('var al' + i + ' = a' + i + ' & 0x1fff;');
  16. src.push('var ah' + i + ' = a' + i + ' >>> 13;');
  17. }
  18. for (i = 0; i < blen; i++) {
  19. src.push('var b' + i + ' = b[' + i + '] | 0;');
  20. src.push('var bl' + i + ' = b' + i + ' & 0x1fff;');
  21. src.push('var bh' + i + ' = b' + i + ' >>> 13;');
  22. }
  23. src.push('');
  24. src.push('out.negative = self.negative ^ num.negative;');
  25. src.push('out.length = ' + len + ';');
  26. for (var k = 0; k < len; k++) {
  27. var minJ = Math.max(0, k - alen + 1);
  28. var maxJ = Math.min(k, blen - 1);
  29. src.push('\/* k = ' + k + ' *\/');
  30. src.push('lo = Math.imul(al' + (k - minJ) + ', bl' + minJ + ');');
  31. src.push('mid = Math.imul(al' + (k - minJ) + ', bh' + minJ + ');');
  32. src.push(
  33. 'mid = (mid + Math.imul(ah' + (k - minJ) + ', bl' + minJ + ')) | 0;');
  34. src.push('hi = Math.imul(ah' + (k - minJ) + ', bh' + minJ + ');');
  35. for (var j = minJ + 1; j <= maxJ; j++) {
  36. i = k - j;
  37. src.push('lo = (lo + Math.imul(al' + i + ', bl' + j + ')) | 0;');
  38. src.push('mid = (mid + Math.imul(al' + i + ', bh' + j + ')) | 0;');
  39. src.push('mid = (mid + Math.imul(ah' + i + ', bl' + j + ')) | 0;');
  40. src.push('hi = (hi + Math.imul(ah' + i + ', bh' + j + ')) | 0;');
  41. }
  42. src.push('var w' + k + ' = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;');
  43. src.push('c = (((hi + (mid >>> 13)) | 0) + (w' + k + ' >>> 26)) | 0;');
  44. src.push('w' + k + ' &= 0x3ffffff;');
  45. }
  46. // Store in separate step for better memory access
  47. for (k = 0; k < len; k++) {
  48. src.push('o[' + k + '] = w' + k + ';');
  49. }
  50. src.push('if (c !== 0) {',
  51. ' o[' + k + '] = c;',
  52. ' out.length++;',
  53. '}',
  54. 'return out;');
  55. return src.join('\n');
  56. }
  57. console.log(genCombMulTo(10, 10));