java - 通过二维数组为一个数存储质因数

标签 java arrays prime-factoring

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

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

最佳答案

你的逻辑是正确的,除了在 for 循环中 i 应该一直到 x 而不是 x/2 如下,

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

getMatrix(60) 的输出:

2   2   
3   1   
4   0   
5   1   
0   0   
0   0   
0   0   
0   0   
0   0   
0   0   

关于java - 通过二维数组为一个数存储质因数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58343161/

相关文章:

php - 计算重复数据并将其存储到变量中

java - 带数组的 if 语句的空指针异常

c++ - 如何在 C++ 中将质因子 vector<int> 减少到 map<int,int>?

primes - 阶乘的素因数分解

python - 具有特定比例的二进制随机数组?

c - 如何删除 C 程序中输出的第一个 *?

java - 创建一个新文件夹并在该文件夹中插入文件。谷歌云端硬盘

java - Android LiveData - 如何在不同的 Activity 中重用相同的 ViewModel?

java - java中的枚举类型是枚举实例 "enclosed"吗?

java - 为什么我得到 java.lang.IllegalStateException : The specified child already has a parent