我有以下方法,在这种情况下显示数字的所有素数 20。我了解该方法的大部分递归行为,但是在打印数字 5 后我有点困惑,为什么 n 回到 10上一次调用时为5时(即执行第三个递归方法时)
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);
}
static int count1 = 1, count2 = 1, count3 = 1, count4 = 1;
public static void primeFactorsR(int n, int m)
{
if(isPrime(n))
{
System.out.println(n);
System.out.println("method1 " +count1++);
}
else
if(n % m == 0)
{
System.out.println("n " + n + " m " + m);
System.out.println("method2: " + count2++);
primeFactorsR(m, m-1);
System.out.println("n " + n + " m " + m);
System.out.println("method3: " + count3++);
primeFactorsR(n/m, (n/m)-1);
}
else
{
System.out.println("n " + n + " m " + m);
//System.out.println("n " + n + " m - 1 " + ( m-1));
System.out.println("method4: " + count4++);
primeFactorsR(n, m-1);
}
}
public static void main(String[] args) {
primeFactors(20);
}
}
输出
n 20 m 19
method4: 1
n 20 m 18
method4: 2
n 20 m 17
method4: 3
n 20 m 16
method4: 4
n 20 m 15
method4: 5
n 20 m 14
method4: 6
n 20 m 13
method4: 7
n 20 m 12
method4: 8
n 20 m 11
method4: 9
n 20 m 10
method2: 1
n 10 m 9
method4: 10
n 10 m 8
method4: 11
n 10 m 7
method4: 12
n 10 m 6
method4: 13
n 10 m 5
method2: 2
5
method1 1
n 10 m 5
method3: 1
2
method1 2
n 20 m 10
method3: 2
2
method1 3
BUILD SUCCESSFUL (total time: 1 second)