通过二维数组存储一个数字的质因数

我正在编写一种方法来存储数字的素因数。我被要求使用二维数组来存储其素因数和因数的数量。


public static int[][] getMatrix (long x){

        int[][] matrix =new int[10][2];

        int count;

        for (int i = 2, j = 0; i <=x / 2; i++) {

           count=0;

           while (x % i == 0) {

               x = x/i;

               count++;

           }

           matrix[j][0] = i;


           matrix[j][1] = count;

           j++;

       }

       return matrix;

   }

但此代码仅将数据存储到数组的第一行。有人可以帮我纠正它或提供其他想法吗?如果我使用下面的代码来输出结果。


for(int row=0;row<b_matrix.length;row++)

        {

            for(int column=0;column<2;column++)

            {

                System.out.print(b_matrix[row][column]+" ");

            }

        }

x=9 我得到这个:


2 0 3 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

x=6 我得到这个:


2 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 

如:6


matrix[0][0]=2  matrix[0][1]=1

matrix[1][0]=3  matrix[1][1]=1 //can't store

如:9


matrix[0][0]=2   matrix[0][1]=0//only output the next row when this equals to 0 

matrix[1][0]=3   matrix[1][1]=2


www说
浏览 99回答 1
1回答

MM们

你的逻辑是正确的,除了在 for 循环中i应该直到x而不是x/2如下,for (int i = 2, j = 0; i <= x; i++)输出getMatrix(60):2&nbsp; &nbsp;2&nbsp; &nbsp;3&nbsp; &nbsp;1&nbsp; &nbsp;4&nbsp; &nbsp;0&nbsp; &nbsp;5&nbsp; &nbsp;1&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;0&nbsp; &nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java