Search code examples
javaalgorithmlogic

Consecutive factor test


A positive number n is consecutive-factored if and only if it has factors, i and j where i > 1, j > 1 and j = i +1. I need a function that returns 1 if its argument is consecutive-factored, otherwise it returns 0.For example, 24=2*3*4 and 3 = 2+1 so it has the function has to return 1 in this case.

I have tried this:

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

    }
}

Can anyone help me with this problem?


Solution

  • First check if its even, then try trial division

    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;
    

    very inefficient, but fine for small numbers. Beyond that try a factorisation algorithm from http://en.wikipedia.org/wiki/Prime_factorization.