斐波纳妾算法的代码实现
今天翻到一套斐波纳妾算法的题目,来了兴致,就写了写玩玩。
题目如下:有一列数1,1,2,3,5,......求第30个数。
发现这有好几总解法,最典型的当然是迭代算法。
目前为止,我发现以下几种解法:
1.简单判断加法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestPaper
{
class Program
{
static void Main(string[] args)
{
int c = 0;
CalMethod cal = new CalMethod();
Console.WriteLine("Input the number:");
c= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("sum is {0}",cal.CalFeiBoNaQie(c)) ;
Console.ReadKey();
}
}
class CalMethod
{
private int sum = 0;
private int a = 0;
private int b = 1;
private int i = 1;
public void CalFeiBoNaQie(int SumCount)
{
// 有一列数1,1,2,3,5....求第30个数
for (int icount = 1; icount <= SumCount; icount++)
{
sum = a + b;
if (icount % 2 == 0)
{
a = sum;
}
else
{
b = sum;
}
}
Console.WriteLine("Sum of {0} Number is {1}", SumCount, sum);
Console.ReadKey();
}
}
}
2.数组计算法
3.迭代算法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestPaper
{
class Program
{
static void Main(string[] args)
{
int c = 0;
CalMethod cal = new CalMethod();
Console.WriteLine("Input the number:");
c= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("sum is {0}", cal.calRecursionTest(c)) ;
Console.ReadKey();
}
}
class CalMethod
{
private int sum = 0;
private int a = 0;
private int b = 1;
private int i = 1;
//private int j = 1;
public int calRecursionTest(int sumCount1)
{
if (sumCount1 == 1 || sumCount1 == 2)
{
sum = i;
return sum;
}
for (int a = 3; a <= sumCount1; a++)
{
sum = calRecursionTest(a - 1) + calRecursionTest(a - 2);
}
//Console.WriteLine("Sum is {0}", sum);
return sum;
}
}
}