描述
Given u0 = 1, u1 = 2 and the relation 6unun+1-5unun+2+un+1un+2 = 0 calculate un for any integer n >= 0.
#Examples
fcn(n) returns un: fcn(17) -> 131072, fcn(21) -> 2097152
Remark: You can take two points of view to do this kata:
the first one purely algorithmic from the definition of un
the second one - not at all mandatory, but as a complement - is to get a bit your head around and find which sequence is hidden behind un.
分析
方法1:根据6*
u
n
∗
u
n
+
1
−
5
∗
u
n
∗
u
n
+
2
+
u
n
+
1
∗
u
n
+
2
=
0
u_n*u_{n+1}-5*u_n*u_{n+2}+u_{n+1}*u_{n+2}=0
un∗un+1−5∗un∗un+2+un+1∗un+2=0 得到:
u
n
+
2
=
6
∗
u
n
∗
u
n
+
1
/
(
5
∗
u
n
−
u
n
+
1
)
u_{n+2}=6*u_n*u_{n+1}/(5*u_n-u_{n+1})
un+2=6∗un∗un+1/(5∗un−un+1)。递推求解即可。
方法2:观察结果序列:
u
0
=
1
,
u
1
=
2
,
u
2
=
4
,
u
3
=
8
u_0=1,u_1=2, u_2=4, u_3=8
u0=1,u1=2,u2=4,u3=8……得到:
u
n
=
2
n
u_n=2^n
un=2n
实现
方法1:
func Fct(n uint) uint {
var a, b float64 = 1, 2 // NOTE 1
var i uint = 2
for ; i <= n; i++ {
a, b = b, 6 * a * b / (5 * a - b)
}
return uint(b)
}
注1:此处必须将运算数转换为浮点型,否则当n比较大时,乘法运算会发生溢出。
方法2:
func Fct(n uint) uint {
return 1 << n
}