Prime Factorization with Recursion in Java.

Prime factors of a number, are all numbers that are prime and multiplied gives you the original number. Let’s take the number 20 for example, all prime factors of 20 are 5, 2, 2. Take a look at the following figure to calculate all prime factors of a number.

here’s the code to calculate prime factors of a number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
 
public class Tester {     
 
    static boolean isPrime(int p)
    {
        for(int i = 2; i < p; i++)
        {
            if(p % i == 0) 
                return false;
        }
        return true;
    }
 
 
   public static void primeFactors(int n)
   {
       primeFactorsR(n, n-1);
   }
 
 
   public static void primeFactorsR(int n, int m)
      {
         if(isPrime(n))
         {
             System.out.println(n);
         }     
         else
            if(n % m == 0)
            {
               primeFactorsR(m, m-1); 
               primeFactorsR(n/m, (n/m)-1);              
            }
            else
            {
               primeFactorsR(n, m-1);
            }
      }   
 
    public static void main(String[] args) {         
 
           primeFactors(20);      
 
    }
}
Share This!

Leave a Reply

Your email address will not be published.