如何使用BigInteger实现矩阵乘法?

时间:2018-10-03 06:48:00

标签: java matrix biginteger

我正在尝试实现矩阵乘法算法,但是在处理BigInteger时遇到问题。

public static void main(String[] args) {
   Scanner scan = new Scanner(System.in);

    System.out.println("Size of Matrix A");
   int tamA1 = scan.nextInt();
   int tamA2 = scan.nextInt();

    System.out.println("Size of Matrix B");
   int tamB1 = scan.nextInt();
   int tamB2 = scan.nextInt();

   BigInteger[][] A = new BigInteger[tamA1][tamA2];
   BigInteger[][] B = new BigInteger[tamB1] [tamB2];
   BigInteger[][] C = new BigInteger[A.length][B[0].length];



    System.out.println("Values of Matrix A");
    for (int i = 0; i < tamA1; i++) {
        for (int j = 0; j < tamA2; j++) {
            A[i][j] = scan.nextBigInteger();
        }
    }

    System.out.println("Values of Matrix B");
    for (int i = 0; i < tamB1; i++) {
        for (int j = 0; j < tamB2; j++) {
            B[i][j] = scan.nextBigInteger();
        }
    }


   if (A[0].length == B.length) {
    for (int i = 0; i < A.length; i++) {
        for (int j = 0; j < B[0].length; j++) {
            for (int k = 0; k < A[0].length; k++) {
                C[i][j] =C[i][j].add(A[i][k].multiply(B[k][j])); // Result
            }
        }
    }

   }

    System.out.println(" C is equal to: ");
    for (int i = 0; i < A.length; i++) {
        for (int j = 0; j < B.length; j++) {
            System.out.print(C[i][j]+" ");
        }
        System.out.println("");
    }


   }

看看这个输出:

Matrix A
2 2
Matrix B
2 2
Values of A
2 2
1 0
Values of B
3 4
5 6
Exception in thread "main" java.lang.NullPointerException
    at matrixmultiplication.MatrixMultiplication.main(MatrixMultiplication.java:56)
C:\Users\Luis Miguel\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1

我不知道为什么可以使用int而不是BigInteger进行此操作。

谢谢。

1 个答案:

答案 0 :(得分:1)

int数组与BigInteger数组之间的“差异”(或实际上是相似之处,取决于您的想法)是,当您创建一个新的整数数组时,所有整数都存在(并且为零),而BigInteger填充了新的null数组。当然不能在add上调用null

有不同的修复方法,例如,您可以用零填充矩阵C,或者可以修改乘法,以使它根本不从C中读取,而是求和成局部变量您将其初始化为零。