大数乘法(分治)

java代码(long需要改变)

import java.util.Arrays;
import java.util.Scanner;
public class 大数乘法 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("输入数据:");
        String a = in.nextLine();
        String b = in.nextLine();
        long num1 = temp(a);
        long num2 = temp(b);
        String result1 =  bigNumberMulti(a, b);
        long result2 = karatsubaMulti(num1, num2);
        System.out.println("普通大数乘法的结果:\n"+a+" * "+b+"\n= "+result1);
        System.out.println("Karatsuba大数乘法结果:\n"+a+" * "+b+"\n= "+result2);

    }



    public static String bigNumberMulti(String a, String b){
        //字符串转换成数组
        char[] charArr1 = a.trim().toCharArray();
        char[] charArr2 = b.trim().toCharArray();
        int[] arr1 = new int[charArr1.length];
        int[] arr2 = new int[charArr2.length];
        for (int i = 0; i < charArr1.length; i++) {
            arr1[i] = charArr1[i] - '0';
        }
        for (int i = 0; i < charArr2.length; i++) {
            arr2[i] = charArr2[i] - '0';
        }

        //大数乘法(不进位)
        int[] result = new int[arr1.length + arr2.length];
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                result[i+j+1] += arr1[i] * arr2[j];
            }
        }
        //处理进位,result是逆序储存的
        for (int k = result.length - 1; k > 0; k--) {
            if(result[k] >= 10 && k != 1){
                result[k-1] += result[k]/10;
                result[k] %= 10;
            }
        }
        String resultStr = "";
        for (int i = 1; i < result.length; i++) {
            resultStr += ""+result[i];
        }
        return resultStr;
    }
    public static long karatsubaMulti(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 halfSize = Math.max(size1, size2) / 2;

        long a = Long.valueOf(String.valueOf(num1).substring(0, size1 - halfSize));
        long b = Long.valueOf(String.valueOf(num1).substring(size1 - halfSize));
        long c = Long.valueOf(String.valueOf(num2).substring(0, size2 - halfSize));
        long d = Long.valueOf(String.valueOf(num2).substring(size2 - halfSize));

        long x0 = karatsubaMulti(b, d);
        long x2 = karatsubaMulti(a, c);
        long x1 = karatsubaMulti((a+b), (c+d)) - x0 - x2;

        return (long)(x2*Math.pow(10, (2*halfSize)) + x1*Math.pow(10, halfSize) + x0);

    }
    public static long temp(String a){
        long result = 0;
        for (int i = 0; i < a.length(); i++) {
            result *= 10;
            result += a.charAt(i) - '0';
        }
        return result;
    }

}

 

 

posted @ 2020-04-12 15:52  德狗咬不过狗  阅读(328)  评论(0编辑  收藏  举报