Java实现分治思想下的大整数数乘

题目:使用分治算法实现两个大整数的相乘

Java实现分治思想下的大整数数乘

实现算法:

public class Main {
    //核心算法
    public static long big_integer_multiplication(long num1, long num2) {
        //递归终止条件
        if(num1 < 10 || num2 < 10) return num1 * num2;

        // 计算拆分长度
        int size1 = String.valueOf(num1).length();
        int size2 = String.valueOf(num2).length();
        int half_N = Math.max(size1, size2) / 2;

        // 拆分为a, b, c, d
        long A = Long.valueOf(String.valueOf(num1).substring(0, size1 - half_N));
        long B = Long.valueOf(String.valueOf(num1).substring(size1 - half_N));
        long C = Long.valueOf(String.valueOf(num2).substring(0, size2 - half_N));
        long D = Long.valueOf(String.valueOf(num2).substring(size2 - half_N));

        // 计算z2, z0, z1, 此处的乘法使用递归
        long z2 = big_integer_multiplication(A, C);
        long z0 = big_integer_multiplication(B, D);
        long z1 = big_integer_multiplication((A + B), (C + D)) - z0 - z2;

        return (long)(z2 * Math.pow(10, (2*half_N)) + z1 * Math.pow(10, half_N) + z0);
    }

    // 测试
    public static void main(String[] args) {
        System.out.println(big_integer_multiplication(1234,4567)); //True
        System.out.println("------------------------------------");
        System.out.println(big_integer_multiplication(123456789,987654321)); //True
        System.out.println("------------------------------------");
        System.out.println(big_integer_multiplication(12345,1234)); //True
    }
    
}

参考资料:

上一篇:ElasticSearch 2 (7) - 基本概念


下一篇:Windows下Python中pip安装Pillow报错总结(转载)