一个小函数参数到100就不行了,如何优化?
function getloop(i)
{
if (i==1)
return 1;
if (i==2)
return 2;
return getloop(i-1) + getloop(i-2);
}
------解决方案--------------------递归也可以优化的 :)
const int SIZE = 100;
static double[] cache = new double[SIZE];
static double Fibo(int n)
{
if (n == 1 || n == 2)
{
Console.WriteLine( "{0} : {1} ", n, 1);
return 1;
}
double n1, n2;
cache[n - 1] = n1 = (cache[n - 1] != 0) ? cache[n - 1] : Fibo(n - 1);
cache[n - 2] = n2 = (cache[n - 2] != 0) ? cache[n - 2] : Fibo(n - 2);
double result = n1 + n2;
Console.WriteLine( "{0} : {1} ", n, result);
return result;
}
static void Main(string[] args)
{
Fibo(SIZE);
}
------解决方案--------------------static void Main(string[] args)
{
long lstart = DateTime.Now.Millisecond;
BigInteger v;
v = fib(100);
long lstop = DateTime.Now.Millisecond;
Console.WriteLine( "fib输入100,输出{0},耗时:{1} ", v, lstop - lstart);
Console.ReadLine();
}
public static BigInteger fib(int no)
{
BigInteger[] arr = new BigInteger[no];
arr[0] = new BigInteger (1);
arr[1] = arr[0];
for (long i = 2; i < no; i++)
{
arr[i] = arr[i - 1] + arr[i - 2];
}
return arr[no - 1];
}
fib输入100,输出354224848179261915075,耗时:0