质因数分解 Java 数组

我必须写一个代码,找到给定数字的质因数分解。代码必须返回一个二维数组,第一行是数字,第二行是幂。我不知道如何将结果保存在这个数组中。


public static long[][] primeFactorization(long l) {

    //n = 6600 = 2^3*3^1*5^2*11^1

    // z[0][4] = 2|3|5|11 - coefficient

    // z[1][4] = 3|1|2|1  - power

    int count = 0;

    int i=2;

    long[][] x = new long[2][];

    while(l%2==0) { 

        l=l/2; 

        count++; //power   8 = 2.2.2 => count = 3

     }

     i++;

     //ToDo: save i=2 in array[0][] = {2,...};

     for (i = 3; i <= Math.sqrt(l); i = i+2) { 

     // While i divides l, print i and divide l 

         while (l%i == 0) { 

                int temp = i; //ToDo: save the divider in array[0][]

                count++; //ToDo: save the power in array[1][]

                l = l/i; 

                i = temp;

            } 

        } 

    return x;

}


慕盖茨4494581
浏览 141回答 2
2回答

潇湘沐

下面的一个没有按预期工作,但在您正在寻找的方向上是正确的。您缺少可以按如下方式完成的填充数组部分。我知道下面的代码有一些小故障,可以通过查看它来修复。但它肯定会给你一个方向。如果您仍然遇到问题,请告诉我们。&nbsp; &nbsp; public static long[][] primeFactorization(long l) {&nbsp; &nbsp; //n = 6600 = 2^3*3^1*5^2*11^1&nbsp; &nbsp; // z[0][4] = 2|3|5|11 - coefficient&nbsp; &nbsp; // z[1][4] = 3|1|2|1&nbsp; - power&nbsp; &nbsp; int count = 0;&nbsp; &nbsp; int i=2;&nbsp; &nbsp; long[][] x = new long[2][10];&nbsp; &nbsp; while(l%2==0) {&nbsp; &nbsp; &nbsp; &nbsp; l=l/2;&nbsp; &nbsp; &nbsp; &nbsp; count++; //power&nbsp; &nbsp;8 = 2.2.2 => count = 3&nbsp; &nbsp; }&nbsp; &nbsp; x[0][0]=2;&nbsp; &nbsp; x[1][0]=count;&nbsp; &nbsp; //ToDo: save i=2 in array[0][] = {2,...};&nbsp; &nbsp; int row=0;&nbsp; &nbsp; int col=1;&nbsp; &nbsp; for (i = 3; i <= l; i = i+2) {&nbsp; &nbsp; &nbsp; &nbsp; count=0; //setting count to zero for every divisor&nbsp; &nbsp; &nbsp; &nbsp; // While i divides l, print i and divide l&nbsp; &nbsp; &nbsp; &nbsp; while (l%i == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++; //ToDo: save the power in array[1][]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; l = l/i;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; x[row][col]=i;&nbsp; &nbsp; &nbsp; &nbsp; x[row+1][col]=count;&nbsp; &nbsp; &nbsp; &nbsp; col++;&nbsp; &nbsp; }&nbsp; &nbsp; return x;}

12345678_0001

如果我猜对了,您会在循环的每次迭代中收到值,并且您想将这些值存储在一个 2 行的二维数组中。所以通常你可以这样做:1)在循环外创建一个整数变量(假设int index = 0;);2)在循环的每次迭代,你可以保存在你的二维数组,这样的结果:x[0][index] = result1;和&nbsp;x[1][index] = result2;3)在循环结束时增加变量索引(索引++);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java