2

正数 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;
        }

    }
}

谁能帮我解决这个问题?

4

2 回答 2

3

先检查是否偶数,再试除法

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的分解算法。

于 2012-11-20T06:12:44.050 回答
2

我已经用上面的代码解决了我的问题。以下是代码。

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++;

            }
        }

        Object ia[] = al.toArray();
        System.out.println("Factors are: " + al);
        int LengthOfList = al.size();
        if (LengthOfList >= 2) {
            int a = ((Integer) ia[0]).intValue();
            int b = ((Integer) ia[1]).intValue();

            if ((a + 1) == b) {
                return 1;
            } else {
                return 0;
            }
        } else {
            return 0;
        }

    }
}
于 2012-11-20T09:18:13.083 回答