如何计算对该函数的递归调用,以及正确答案是什么

How can I calculate the recursive calls to this function and what will be the correct answer to it?

本文关键字:调用 是什么 答案 递归 何计算 计算 函数      更新时间:2023-10-16

如何计算对此函数的递归调用,正确答案是什么??????

int func(x,y)
{
  if (x % y == 0) return y;
  x = x % y; 
  return func(y,x);
}

我需要一个公式,或者一个解释或一般表达,因为它在这里真的很困惑?????

使用全局变量是一个简单的解决方案。

    int i;
    main()
    {
        i=0; //if you want to avoid main call just start with i=-1     
        //if you are using loop and then calling function in loop ,  
        //make i value zero or -1 to know how many recursive calls are made to particular call.  
        func(x,y);
        //now i consists number of recursive calls made.
    }
    int func(int x,int y)
    {
        i++;
        if (x % y == 0) return m;
        x = x % y; 
        return func(y,x);
    }

首先,您的代码不会编译。您需要提供xy类型,如intlong。其次是你;可能想在做其他事情之前订购xy。比如:

int func(int x, int y) {
    int mx = max(x, y);
    int mn = min(x, y);
    // as above with mx for x and mn for y
}

你是怎么知道电话号码的?

有两种方法。

  1. 插入代码:添加一个计数到函数顶部的变量,当函数完成时,打印计数。

  2. 自己执行代码:假装是计算机,计算每一步并遵循决策路径。对各种输入进行此操作,看看它会给您带来什么结果。计算它所走的步数。请记住,要考虑返回到的位置-递归函数返回到自身。

如何找到正确答案?

与上面类似。

  1. 运行代码并打印结果
  2. 遍历代码,弄清楚每一步的结果是什么,以及最终结果是什么

我会将您的函数更改为:

int func(int x, int y, int& n)//I asume x and y are ints
{
  if (x % y == 0) return y;
  x = x % y; 
  return func(y,x, n+1);//not sure if I understood question correctly, so I think you need to change n value here.
}
int func(int x, int y, int& n)//I asume x and y are ints
{
    ++n;//not sure if I understood question correctly, it may be you need this place for count variable increment
    if (x % y == 0) return y;
    x = x % y; 
    return func(y,x, n);
}

要使用该功能,您需要:

int x = 1000, y = 7, n = 0;
int ret = func(x, y, n);  //n must be zero

顺便说一句,你也可以使用全局变量,但这不是最好的体验,所以最好再给函数传递一个参数。