本文介绍了如何分析一个递归源$ C ​​$ CS手?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何分析一个递归源$ C ​​$ CS手?

例如,我设计了一种技术,通过手工分析迭代源$ C ​​$ C是这样的:

  INT事实(INT N)
{
 INT F = 0;
 INT I = 0;
 如果(N下; = 1)
 {
  返回1;
 } F = 1;
 我= 2;
 对于(i = 2; I< = N;我++)
 {
  F * = I;
 } 返回F;
}---------------------------
  I F新-F
---------------------------
---------------------------
---------------------------

对于每一个我,我可以分析和手工计算旧-F和新-F的值并填写表格看,如果日常工作正常。

但我怎么可以用手分析递归程序?

  INT事实(INT编号){
    INT温度;    如果(数字< = 1)返回1;    TEMP =号*事实( - 1);
    返回温度;
}


解决方案

由于堆栈上的递归值存储你需要分析它的2路

第1次是:执行递归直到达到终止条件

第2次:直到堆栈为空收集值

  1日下降了2次
---------------------------------
N = 6 TMP = 6 * 120 = 720< - 结果
N = 5 TMP = 5 * 24 = 120
n = 4的TMP = 4 * 6 = 24
n = 3的TMP = 3 * 2 = 6
n = 2的TMP = 2 * 1 = 2
N = 1结束

How can I analyze a recursive source codes by hand?

For example, I have devised a technique for analyzing iterative source code by hand like this:

int fact(int n) 
{ 
 int f = 0; 
 int i = 0; 
 if (n<=1)  
 {  
  return 1; 
 } 

 f = 1; 
 i = 2; 
 for (i=2; i<=n ; i++) 
 { 
  f *= i; 
 } 

 return f; 
}

---------------------------
  i         f       new-f
---------------------------
---------------------------
---------------------------

For each 'i' I can analyze and calculate the values of old-f and new-f by hand and fill up the table to see if the routine is working correctly.

But how can I analyze recursive routines by hand?

int fact(int number) {
    int temp;

    if(number <= 1) return 1;

    temp = number * fact(number - 1);
    return temp;
}
解决方案

Since recursion stores values on the stack you need to analyze it 2-way

1st pass is: do the recursion until the termination condition is reached.

2nd pass: collect the values until the stack is empty.

1st down  2nd up
---------------------------------
n = 6     tmp = 6 * 120 = 720 <- result
n = 5     tmp = 5 * 24 = 120
n = 4     tmp = 4 * 6 = 24
n = 3     tmp = 3 * 2 = 6
n = 2     tmp = 2 * 1 = 2
n = 1     end

这篇关于如何分析一个递归源$ C ​​$ CS手?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 18:02