For the sake of getting a better understanding of recursion, compile and run this code:
public class recursiontests {
static int count1;
static int count2;
static int count3;
static int count4;
public static void primeFactors(int n)
{
primeFactorsR(n, n-1,0);
}
public static boolean isPrime(int p)
{
for(int i = 2; i < p; i++)
{
if(p % i == 0) return false;
}
return true;
}
public static void primeFactorsR(int n,int m,int rec) {
String indent = "";
for(int i=0;i<rec;i++)
indent+="|";
if(isPrime(n))
{
System.out.println(indent+n);
System.out.println(indent+"method1 " +count1++);
}
else if(n % m == 0)
{
System.out.println(indent+"n " + n + " m " + m);
System.out.println(indent+"method2: " + count2++);
primeFactorsR(m, m-1, rec+1);
if(rec!=0)
System.out.println(indent);
System.out.println(indent+"n " + n + " m " + m);
System.out.println(indent+"method3: " + count3++);
primeFactorsR(n/m, (n/m)-1, rec+1);
if(rec!=0)
System.out.println(indent);
}
else
{
System.out.println(indent+"n " + n + " m " + m);
System.out.println(indent+"method4: " + count4++);
primeFactorsR(n, m-1, rec+1);
if(rec!=0)
System.out.println(indent);
}
}
public static void main(String[] args) {
primeFactors(20);
}
}
It should produce an output similar to this:
n 20 m 19
method4: 0
|n 20 m 18
|method4: 1
||n 20 m 17
||method4: 2
|||n 20 m 16
|||method4: 3
||||n 20 m 15
||||method4: 4
|||||n 20 m 14
|||||method4: 5
||||||n 20 m 13
||||||method4: 6
|||||||n 20 m 12
|||||||method4: 7
||||||||n 20 m 11
||||||||method4: 8
|||||||||n 20 m 10
|||||||||method2: 0
||||||||||n 10 m 9
||||||||||method4: 9
|||||||||||n 10 m 8
|||||||||||method4: 10
||||||||||||n 10 m 7
||||||||||||method4: 11
|||||||||||||n 10 m 6
|||||||||||||method4: 12
||||||||||||||n 10 m 5
||||||||||||||method2: 1
|||||||||||||||5
|||||||||||||||method1 0
||||||||||||||
||||||||||||||n 10 m 5
||||||||||||||method3: 0
|||||||||||||||2
|||||||||||||||method1 1
||||||||||||||
|||||||||||||
||||||||||||
|||||||||||
||||||||||
|||||||||
|||||||||n 20 m 10
|||||||||method3: 1
||||||||||2
||||||||||method1 2
|||||||||
||||||||
|||||||
||||||
|||||
||||
|||
||
|
It is the same code as what you had (for the most part, I gave it a different name), but I added something to the output to make the levels of recursion more visible. Each | represents one level deep of recursion. Every time a line is one level deeper than the previous line, it means the method was called recursively, and each time a line is one level less than the previous line, it means it has returned from where the method was called recursively.