【问题标题】:Iteration methods for a recursive sequence递归序列的迭代方法
【发布时间】:2017-10-13 23:17:20
【问题描述】:

递归序列a(n)=-a(n-1)+n-1怎么解? 我尝试了前向和后向迭代,但无法为 a(n) 找到明确的解决方案。

【问题讨论】:

  • 这是一个编程网站,而不是数学网站,所以你在这里的答案可能是代​​码。您是否希望用一种语言来实现这一点?
  • 我希望最终将它实现到 Java 或 python 中
  • 你的基本情况是什么?目前没有可解决的n
  • 哎呀。 a(0)=7。

标签: recursion discrete-mathematics


【解决方案1】:

你的第一步应该是写出一个结果表

f(n)=x

n | x
-----
0 | 7
1 | -7     (-7 + 1 - 1)
2 | 8      ( 7 + 2 - 1)
3 | -6     (-8 + 3 - 1)
4 | 9      ( 6 + 4 - 1)
5 | -5     (-9 + 5 - 1)
6 | 10     ( 5 + 6 - 1)
7 | -4     (-10 + 7 - 1)
8 | 11     ( 4 + 8 - 1)
9 | -3     (-11 + 9 - 1)

您应该会看到一种模式正在出现。每对解决方案[(0, 1), (2, 3), (4, 5), ...] 相差 14,从(7, -7) 开始,每两点n 递增一个。我们可以概括一下:

f(0) = 7
f(n) = 7 + k - 14 * b
  where k is the increment value (each 1 k per 2 n)
        b is 1 when n is odd, else 0.

现在我们只需要根据n 定义kbk应该不会太难吧,看看吧:

n | k
0 | 0
1 | 0
2 | 1
3 | 1

这让你想起了什么吗?那是一个有底的 div2。

7 + (n // 2) - 14 * b

现在b

n | b
0 | 0
1 | 1
2 | 0
3 | 1

在我看来,这就像mod 2!模是除法问题的余数,是检查数字是偶数还是奇数的好方法。我们也在寻找普通的模数,因为当n 是奇数时我们想要b==1,反之亦然。

f(0) = 7
f(n) = 7 + (n // 2) - 14 * (n%2)
  where (//) is the floor division function
        (%) is the modulo function

现在我们可以将所有这些放在一个函数中。在 Go 中是:

func f(n int) int {
    return 7 + n/2 - 14 * (n % 2)
}

在 Python 中是

def f(n):
    return 7 + n//2 - 14 * (n%2)

在 Haskell 中我们有

f :: Int -> Int
f n = 7 + n `div` 2 - 14 * (n `mod` 2)

或者,由于 Haskell 实现递归非常好,简单...

f :: Int -> Int
f 0 = 7
f n = f (n-1) + n - 1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-24
    • 2016-07-21
    • 2017-03-08
    • 1970-01-01
    • 2016-04-07
    • 2016-11-10
    相关资源
    最近更新 更多