Java实现大数乘法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Jin_Kwok/article/details/81947926

今天无意中看到一个C++实现的大数乘法,感觉不顺眼,遂用Java写了一个。

这里所说的大数,是指编程语言提供的基本数据类型无法表达的数据,比如1000位的数据,这样的数据通常用字符串或者数组表示,比如:12345678899878676768787786867868762342。两个大数之间的乘法实现参考如下:

import java.util.Arrays;

public class BigData
{

    public static void main(String[] args)
    {
        // TODO Auto-generated method stub

        int[] a = {2, 5, 6, 7, 8, 9, 1, 2, 3, 4};
        int[] b = {2, 5, 6, 7, 8, 9, 1};
        int[] result = new int[a.length + b.length - 1];
        bigDataComput(a, b, result);

    }

    public static void bigDataComput(int[] num1, int[] num2, int[] result)
    {

        int carry = 0;

        for (int i = num1.length - 1; i >= 0; i--)
        {
            carry = 0;

            for (int j = num2.length - 1; j >= 0; j--)
            {
                int temp = num1[i] * num2[j] + carry + result[i + j];
                result[i + j] = temp % 10;
                carry = temp / 10;
            }
            // 最后仍有进位,则保存进位到高位
            if (carry != 0)
            {
                result[i - 1] = carry;
            }
        }
        // 打印计算结果
        System.out.println(Arrays.toString(result));
    }

}

猜你喜欢

转载自blog.csdn.net/Jin_Kwok/article/details/81947926