我一直在尝试修改nextfactor方法一段时间以获得所需的结果。基本上,我应该排除所有偶数,除了2但我仍然无法做到。该课程的代码如下。任何帮助表示赞赏。此致
public class FactorGenerator
{
private int number;
public FactorGenerator(int num)
{
// initialise instance variables
number = num;
if (number <= 2) {
System.out.println("Wrong argument");
}
}
public boolean hasMoreFactors()
{
if (number >= 2) {
return true;
} else {
return false;
}
// return (number >= 2);
}
public boolean isDivisible(int otherNumber)
{
if (number % otherNumber == 0) {
return true;
} else {
return false;
}
}
/**
* Determine next factor.
* pre-condition: call only if hasMoreFactors
* returns true
*
* @return a factor of the object's number
*/
public int nextFactor()
{
int triedFactor = 2;
if(number % nextFactor == 0)
while (! isDivisible(triedFactor)) {
triedFactor = triedFactor+1;
}
number = number / triedFactor;
return triedFactor;
}
}
答案 0 :(得分:1)
使用
triedFactor = triedFactor==2 ? 3 : triedFactor+2;
而不是
triedFactor = triedFactor+1;
答案 1 :(得分:1)
while (! isDivisible(triedFactor)) {
if(triedFactor == 2) {
triedFactor = triedFactor+1;
} else {
triedFactor = triedFactor+2;
}
}
答案 2 :(得分:-3)
Exclude all even except 2 ? This is code
public ArrayList GetExeptEven(int upperBound){
ArrayList list=new ArrayList();
list.add(1);
list.add(2);
for(int i=3;i<=upperBound;i=i+2)
list.add(i);
return list;
}