Java - 质因数 - 修复技巧?
Java - Prime Factors - Tip to fix?
我想用素数填充列表。这里有什么问题?
public class factorClass {
private ArrayList<Integer> factors = new ArrayList<>();
// constructor populates array of factors for a given number
public factorClass(int factorThis) {
int test = 2;
while (factorThis > 1 ) {
if (factorThis % test == 0) { //factor found
factors.add(test); //add factor to array
factorThis = factorThis / test; //quotient is new number to factor
} else {
testFactor++;// try next integer
}
}
}
有两处错误:
您首先测试因子 3,这意味着您永远找不到 2 个因子。
你的循环条件 - testFactor > 1
- 是错误的。 testFactor
不断增长,因此循环只会在 testFactor
溢出到负值时终止。您应该在 NumberToFactor
变为 1 时终止。即将条件更改为 NumberToFactor > 1
。
哦,还有另一个问题 - Factors
似乎是一个构造函数,但它出现在一个不同名称的 class 中 - factorClass
。构造函数必须与 class.
同名
我想用素数填充列表。这里有什么问题?
public class factorClass {
private ArrayList<Integer> factors = new ArrayList<>();
// constructor populates array of factors for a given number
public factorClass(int factorThis) {
int test = 2;
while (factorThis > 1 ) {
if (factorThis % test == 0) { //factor found
factors.add(test); //add factor to array
factorThis = factorThis / test; //quotient is new number to factor
} else {
testFactor++;// try next integer
}
}
}
有两处错误:
您首先测试因子 3,这意味着您永远找不到 2 个因子。
你的循环条件 -
testFactor > 1
- 是错误的。testFactor
不断增长,因此循环只会在testFactor
溢出到负值时终止。您应该在NumberToFactor
变为 1 时终止。即将条件更改为NumberToFactor > 1
。
哦,还有另一个问题 - Factors
似乎是一个构造函数,但它出现在一个不同名称的 class 中 - factorClass
。构造函数必须与 class.