斐波那契数列

  • 斐波那契数列(Fibonacci sequence),又称黄金分割数列,因数学家莱昂纳多·斐波那契(Leonardo Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列”
  • F(0)=1,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*)

实例:循环+数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static int k = 140;// 输出斐波那契数列数量(测试上限为:140) 可更改

decimal[] si = new decimal[k]; //存储计算值以节省时间
decimal fib(int a) //方法
{
if(a <= 1) return a;
if(si[a] != 0) return si[a];
return si[a] = fib(a-1)+fib(a-2);
}

static void Main(string[] args)
{
HelloWorld c = new HelloWorld();
for(int n = k-1;n >= 0;n--){ //倒序输出
Console.WriteLine(c.fib(n));//调用方法fib
}
Console.ReadKey();
}
}
}

阶乘

  • 一个正整数的阶乘(factorial)是所有小于及等于该数的正整数的积,并且0的阶乘为1。自然数n的阶乘写作n!
  • 即n!=1×2×3×…×(n-1)×n。阶乘亦可以递归方式定义:0!=1,n!=(n-1)!×n

使用递归函数计算一个数的阶乘:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System;

namespace CalculatorApplication
{
class NumberManipulator
{
public int factorial(int num)
{
/* 局部变量定义 */
int result;

if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}

static void Main(string[] args)
{
NumberManipulator n = new NumberManipulator();
//调用 factorial 方法
Console.WriteLine("6 的阶乘是: {0}", n.factorial(6));
Console.WriteLine("7 的阶乘是: {0}", n.factorial(7));
Console.WriteLine("8 的阶乘是: {0}", n.factorial(8));
Console.ReadLine();

}
}
}