Print a string of fibonacci recursively in C#

前端 未结 11 687
你的背包
你的背包 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:30

    public static class Golden
    {
        public static IEnumerable Fibonacci()
        {
            var a = 0L;
            var b = 1L;
            var s = 0L;
            yield return a;
            while (a < long.MaxValue - b)
            {
                yield return b;
                s = a + b;
                a = b;
                b = s;
            }
        }
    
        public static IEnumerable FibonacciR()
        {
            IEnumerable Fibo(long a, long b)
            {
                yield return a;
                if (a < long.MaxValue - b)
                {
                    foreach (var v in Fibo(b, a + b))
                    {
                        yield return v;
                    }
                }
            }
            return Fibo(0, 1);
        }
    }
    

提交回复
热议问题