Search code examples
javaalgorithmrecursionprime-factoring

Recursive prime factor algorithm in java


I am trying to implement a simple algorithm in java for finding all prime number factors of an integer passed by parameter:

private static ArrayList<Integer> lstPrime= new ArrayList<Integer>();

    public static ArrayList primeFactors(int n) {

        if (isPrime(n)) 
        {
            lstPrime.add(n);
        }

        for (int i=2; i<=(Math.sqrt(n)); i++)
        {
            if (n % i == 0)
            {
                lstPrime.addAll(primeFactors(n/i));
                return lstPrime;
            }
        }
        return lstPrime;
    }

Funny thing is that if I pass 81 as n, the result will be : 3, 3, 3, 3, 3, 3, 3, 3 while it SHOULD be : 3, 3, 3, 3 (3^4=81)


Solution

  • OK! I think I have solved my problem, except for the fact that the ArrayList is declared outside the recursive function. I cannot imagine any other way of treating the list because since this is a recursive function, if the list would be declared inside the function, it would be instantiated again and again each time recursion occurs. Here is what I have so far, feel free to criticize:

    public static ArrayList<Integer> list = new ArrayList<Integer>();
    
    public static void primeFactors(int n) {
        if (isPrime(n)) 
        {
            list.add(n);
            return;
        }
    
        int i = 2;
        while (i < n/2)
        {
            if (n % i == 0)
            {
                 if (isPrime(i))
                 {
                     primeFactors(n/i);
                     list.add(i);
                     return;
                 } 
            }
            i++;
        }
        return;
    }
    

    For example, this code will produce: 3,3,3,3 for primeFactors(81) and 5,3,2,2 for primeFactors(60) and so on...