你的第一步应该是写出一个结果表
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 定义k 和b。 k应该不会太难吧,看看吧:
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