Multiplication of very long integers

后端 未结 7 1015
耶瑟儿~
耶瑟儿~ 2021-02-09 06:04

Is there an algorithm for accurately multiplying two arbitrarily long integers together? The language I am working with is limited to 64-bit unsigned integer length (maximum int

相关标签:
7条回答
  • 2021-02-09 06:48

        //Here is a JavaScript version of an Karatsuba Algorithm running with less time than the usual multiplication method
        
        function range(start, stop, step) {
            if (typeof stop == 'undefined') {
                // one param defined
                stop = start;
                start = 0;
            }
            if (typeof step == 'undefined') {
                step = 1;
            }
            if ((step > 0 && start >= stop) || (step < 0 && start <= stop)) {
                return [];
            }
            var result = [];
            for (var i = start; step > 0 ? i < stop : i > stop; i += step) {
                result.push(i);
            }
            return result;
        };
        function zeroPad(numberString, zeros, left = true) {
            //Return the string with zeros added to the left or right.
            for (var i in range(zeros)) {
                if (left)
                    numberString = '0' + numberString
                else
                    numberString = numberString + '0'
            }
        
            return numberString
        }
        function largeMultiplication(x, y) {
            x = x.toString();
            y = y.toString();
        
            if (x.length == 1 && y.length == 1)
                return parseInt(x) * parseInt(y)
        
            if (x.length < y.length)
                x = zeroPad(x, y.length - x.length);
        
            else
                y = zeroPad(y, x.length - y.length);
        
            n = x.length
            j = Math.floor(n/2);
        
            //for odd digit integers
            if ( n % 2 != 0)
                j += 1    
            var BZeroPadding = n - j
            var AZeroPadding = BZeroPadding * 2
        
            a = parseInt(x.substring(0,j));
            b = parseInt(x.substring(j));
            c = parseInt(y.substring(0,j));
            d = parseInt(y.substring(j));
        
            //recursively calculate
            ac = largeMultiplication(a, c)
            bd = largeMultiplication(b, d)
            k = largeMultiplication(a + b, c + d)
            A = parseInt(zeroPad(ac.toString(), AZeroPadding, false))
            B = parseInt(zeroPad((k - ac - bd).toString(), BZeroPadding, false))
            return A + B + bd
        }
        //testing the function here
        example = largeMultiplication(12, 34)
        console.log(example)

    0 讨论(0)
提交回复
热议问题