我正在尝试创建一种将数字 n 分解为素数乘积的方法。例如,因式分解 12 将得到 3 x 2^2。第一个代码块将 n 分解为松散数,因此 12 = 3 x 2 x 2 并将它们放入 f 中。然后,第二个 block 应该将这些数字作为幂而不是松散数字存储在 p 中,方法是将指数计算为数字在 f 中出现的次数,因此 3^1 x 2^2 而不是 3 x 2 x 2。是通过存储数字的底数和指数的 Power 对象完成的。
但是由于某种原因,此代码不断返回空数组。而且看了很多遍我还是不明白为什么会这样。我是否做错了什么或者我误解了什么?
/**
* factorize n
*
* @param n the number to 'powerize'
* @modifies none
* @pre {@code 2 <= n}
* @return factorization of n
*/
public static List<Power> factorize(int n) {
List<Integer> f = new ArrayList<Integer>(); // f are factors
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
f.add(i);
n /= i;
}
}
List<Power> p = new ArrayList<Power>(); // p are the factors with powers
for (int j = 2; j <= n; j++) { //j will be the base
int e = 0; //exponent
for (int k = 0; k <= f.size(); k++) {
if (f.get(k) == j) {
e++;
}
}
p.add(new Power(j, e));
}
return p; //returns factors in powered form
}
如果有必要,我将添加 Power 对象的代码。
/**
* Record containing a base and an exponent.
*
* @inv {@code 0 <= base && 0 <= exponent}
*/
public static class Power { // BEGIN RECORD TYPE
/**
* The base.
*/
public int base;
/**
* The exponent.
*/
public int exponent;
/**
* Constructs a Power with given base and exponent.
*
* @param base the base
* @param exponent the exponent
* @pre {@code 0 <= base && 0 <= exponent}
* @post {@code \result.base == base && \result.exponent == exponent}
*/
public Power(int base, int exponent) {
this.base = base;
this.exponent = exponent;
}
} // END RECORD TYPE
最佳答案
如果您进行调试,您将看到在第一个 for
循环后您的 n
变量值为 1
。这就是为什么第二个周期根本没有开始
关于java - 尽管添加了对象,为什么我的数组列表仍为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42395039/