遞回解階乘、費氏級數
想起來以前在學c++時曾經寫過的程式與大家分享,呵。
1.階乘解法
0!=1
5! = 5 * 4 * 3 * 2 * 1
x! = x * (x - 1) * (x - 2) * (x - 3) * ..... * 1
1
private int Factor(int x)
2
{
3
if (x == 0) return 1;
4
else
5
return Factor(x - 1) * x;
6
}
private int Factor(int x) 2
{ 3
if (x == 0) return 1; 4
else 5
return Factor(x - 1) * x; 6
}2.費氏級數解法
f(1) = 1
f(2) = 1
f(x) = f(n - 1) + f(n - 2)
1
private int Fib(int x)
2
{
3
if (x == 1 || x == 2) return 1;
4
else
5
return Fib(x - 1) + Fib(x - 2);
6
}
private int Fib(int x) 2
{ 3
if (x == 1 || x == 2) return 1; 4
else 5
return Fib(x - 1) + Fib(x - 2); 6
}不過工作後有前輩指出盡量少用遞回寫法聽說也許是因為耗資源的關係吧。
