@@ -465,6 +465,53 @@ BigInteger.prototype.multiply = function(n) {
465465 return new BigInteger ( partial , this . _s !== n . _s ? - 1 : 1 ) ;
466466} ;
467467
468+ // Multiply a BigInteger by a single-digit native number
469+ // Assumes that this and n are >= 0
470+ BigInteger . prototype . multiplySingleDigit = function ( n ) {
471+ if ( n === 0 || this . _s === 0 ) {
472+ return BigInteger . ZERO ;
473+ }
474+ if ( n === 1 ) {
475+ return this ;
476+ }
477+ 478+ if ( this . _d . length === 1 ) {
479+ var digit = this . _d [ 0 ] * n ;
480+ if ( digit > 9 ) return new BigInteger ( [ ( digit % 10 ) | 0 , ( digit / 10 ) | 0 ] , 1 ) ;
481+ return BigInteger . small [ digit ] ;
482+ }
483+ 484+ if ( n === 2 ) {
485+ return this . add ( this ) ;
486+ }
487+ if ( this . isUnit ( ) ) {
488+ return BigInteger . small [ n ] ;
489+ }
490+ 491+ var a = this . _d ;
492+ var al = a . length ;
493+ 494+ var pl = al + 1 ;
495+ var partial = new Array ( pl ) ;
496+ for ( var i = 0 ; i < pl ; i ++ ) {
497+ partial [ i ] = 0 ;
498+ }
499+ 500+ var carry = 0 ;
501+ for ( var j = 0 ; j < al ; j ++ ) {
502+ var digit = n * a [ j ] + carry ;
503+ carry = ( digit / 10 ) | 0 ;
504+ partial [ j ] = ( digit % 10 ) | 0 ;
505+ }
506+ if ( carry ) {
507+ var digit = carry ;
508+ carry = ( digit / 10 ) | 0 ;
509+ partial [ j ] = digit % 10 ;
510+ }
511+ 512+ return new BigInteger ( partial , 1 ) ;
513+ } ;
514+ 468515BigInteger . prototype . square = function ( ) {
469516 return this . multiply ( this ) ;
470517} ;
@@ -522,7 +569,7 @@ BigInteger.prototype.divMod = function(n) {
522569 var guess = 9 ;
523570 }
524571 do {
525- var check = a . multiply ( small [ guess ] ) ;
572+ var check = a . multiplySingleDigit ( guess ) ;
526573 if ( check . compareAbs ( part ) <= 0 ) {
527574 break ;
528575 }
0 commit comments