正数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;
}
}
}
有人能帮我解决这个问题吗?
最佳答案
先检查一下是否均匀,然后再试试审判庭
if(n%2!=0) return 0;
for(i=2;i<sqrt(n);++i) {
int div=i*(i+1);
if( n % div ==0) { return 1; }
}
return 0;
效率很低,但数量少就可以了除此之外,尝试使用http://en.wikipedia.org/wiki/Prime_factorization中的因子分解算法。