使用递归生成序列的正确输出。

huangapple go评论73阅读模式
英文:

Using recursion to generate the correct output for a sequence

问题

我尝试使用递归来解决一个返回序列的第n个数字的函数。它的规则如下:

该序列以数字4开始。随后的每个数字都是前一个数字的三倍,然后再加1。例如,以下是序列的前几个数字:1, 4, 13, 40, 121, 364等。

int recursive_sequence(int n)
{
    if (n == 1)
    {
        return 1; // 这是基本情况
    }
    else
    {
        return 4 + (3 * (n-1) + 1) + recursive_sequence(n-1); // 这是递归情况
    }
}

我尝试通过从数字4开始,然后"前一个数字的三倍,再加1",然后调用递归函数来计算下一个数字。例如,如果输入n为4,那么正确的输出应该是40,因为3 * (13) + 1 = 40。然而,用我的代码作为示例,我得到了34。我做错了什么?如果可能的话,请在您的答案中包括一个示例(将不胜感激!)。

英文:

I'm trying to use recursion to solve a function that returns the nth number of a sequence. It goes as follows:

The sequence begins with the number 4. Every following number is three times the previous number, then added by 1. For instance, these are the first several numbers of the sequence: 1, 4, 13, 40, 121, 364, etc.

int recursive_sequence(int n)
{
    if (n == 1)
    {
        return 1; // This is base case
    }
    else
    {
        return 4 + (3 * (n-1) + 1) + recursive_sequence(n-1); // This is recursive case
    }
}

I attempted this by starting with the number 4, then "3 times the previous number, add 1", then calling the recursion function to go down to the next number. If "n" is inputted as "4", for example, then the correct output would be 40 since 3 * (13) + 1 = 40. However, as an example, with my code, I got 34. What am I doing wrong? If you can, please include an example in your answer (it would be greatly appreciated!).

答案1

得分: 2

第一个数字是1,而不是4。因此,你应该从1开始。

然后,你可以简单地将其表示为“前一个数乘以3,再加1”作为一个公式。

int recursive_sequence(int n)
{
    if (n == 1)
    {
        return 1; // 从1开始
    }
    else
    {
        return 3 * recursive_sequence(n-1) + 1; // 前一个数乘以3,再加1
    }
}
英文:

The first number is 1, not 4. Therefore, you should start from 1.

Then, you should simply write "3 times the number before it, add 1" as a formula.

int recursive_sequence(int n)
{
    if (n == 1)
    {
        return 1; // start from 1
    }
    else
    {
        return 3 * recursive_sequence(n-1) + 1; // 3 times the number before it, add 1
    }
}

huangapple
  • 本文由 发表于 2023年3月12日 13:15:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711180.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定