【发布时间】:2014-03-24 12:37:56
【问题描述】:
我被要求解决这个问题:
编写一个函数,将两个数字
n1和n2作为输入(使用n2>n1) 并返回对应于的最大素因子数组n1和n2之间的每个数字。
我的尝试如下所示,但我的代码无法正常工作。它不是从n1 迭代到n2。我怎样才能正确?
public static class A{
static int testcase1=5;
static int testcase2=10;
public static void main(String args[]){
A testInstance = new A();
int[] result = testInstance.getLpfd(testcase1,testcase2);
System.out.print("{");
for (int i=0;i<result.length;i++){
if (i>0)
System.out.print(",");
System.out.print(result[i]);
}
System.out.println("}");
}
public int[] getLpfd(int n1,int n2){
int current=0;
int[] factors = new int[20];
for(int j=n1;j<=n2;j++){
for (int i = 2; i <= j; i++){
while(j % i == 0){
factors[current]=i;
j /= i;
current++;
}
}
}
return factors;
}
}
}
【问题讨论】:
-
好吧,首先你要在 while 循环中修改你的第一个 for 循环变量 (j)。这没有帮助。
标签: java arrays prime-factoring