【发布时间】:2012-11-20 05:46:56
【问题描述】:
一个正数 n 是consecutive-factored 当且仅当它有因子 i 和 j 其中i > 1, j > 1 and j = i +1。我需要一个 returns 1 的函数,如果它的参数是连续因子,否则它是 returns 0。例如,24=2*3*4 和 3 = 2+1 所以在这种情况下它的函数必须是 return 1。
我试过这个:
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number %i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a =al(0);
int b = al(1);
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}
谁能帮我解决这个问题?
【问题讨论】:
-
我首先要说,如果存在这样一对因素,那么它就是独一无二的。这应该指向它们的价值。
-
提示 2:您可以使用
Math.sqrt、Math.floor和Math.ceil为您带来好处。 -
@MukulGoel 我已经添加了我尝试过的代码,但它不起作用。
-
@all : 人们我认为我们应该只警告他们不知道投反对票的新人,我们应该通过警告不要再这样做来鼓励他们,但不要通过简单的投反对票来阻止他们跨度>