递归与尾递归
下面两个程序是scheme写的计算阶乘的递归和尾递归实现 线性递归: (define (factorial n) (if (=n 1) 1 (* n (factorial (- n 1))))) 尾递归: (define (factorial n) (fact-iter 1 1 n)) (define (fact-iter product counter max-count) (if (> counter max-count) product (fact-iter (* counter product) (+ counter 1) max-count))) 用C写出来就是这样的: 线性递归: long factorial(long n) { return(n == 1) ? 1 : n * factorial(n - 1); } 尾递归: long fact_iter(long product, long counter, long maxcount) { return (counter > maxcount) ? product : fact_iter(product*counter, counter+1, maxcount); } long factorial(long n) { return fact_iter(1, 1, n); } 线性递归程序基于阶乘的递归定义,即