Print a string of fibonacci recursively in C#

前端 未结 11 688
你的背包
你的背包 2020-12-29 16:05

Can that be done with no while loops?

static void Main(string[] args)
{
    Console.WriteLine(\"Please enter a number\");
    int number = Convert.ToInt32(C         


        
11条回答
  •  温柔的废话
    2020-12-29 16:37

    I realize this may be an old thread, but oh well I think this kinda question is good in its nature.

    Using while loop/or recursive way of doing is not the optimal way of doing as it takes a O(2^n) times. A better way to do this is using what is already in memory like below. This should take at most O(n) time.

    Cheers!

     static double fibDynamic(int n)
            {
                double[] array = new double[n];
                array[0] = array[1] = 1;
    
                for(int i = 2; i < n; i++)
                {
                    array[i] = array[i - 1] + array[i - 2];
                }
                return array[n-1];
            }
    

提交回复
热议问题