c#求取斐波那契数列中第一个大于2147483647的数

using System;


namespace ConsoleApp1
{
    //斐波那契数
    //请查找集合中第一个大于2147483647的数
    class Program
    {
        //递归写法
        public static ulong Foo(int n)
        {
            if (n < 2)
            {
                return 1;
            }
            else
            {
                return Foo(n - 2) + Foo(n - 1);
            }
        }
        //循环写法
        //ulong     0 到 18,446,744,073,709,551,615
        public static ulong Foo2(int n)
        {
            ulong a = 1;
            ulong b = 1;
            if (n == 1 || n == 2)
            {
                return 1;
            }
            else
            {
                for (int i = 3; i <= n; i++)
                {
                    ulong c = a + b; //两数之和
                   // Console.WriteLine("b={0}", a);
                    b = a; //之前的和放在b中
                   // Console.WriteLine("c={0}", c);
                    a = c; //当前的和放到a中
                }
                return a;

            }

        }
        static void Main(string[] args)
        {
            // 1,1,2,3,5,8,13,21,34
            Console.WriteLine("斐波那契数第30位:");
            Console.WriteLine(Foo(30));
            //Console.WriteLine(Foo2(30));
            //请查找集合中第一个大于 2147483647 的数--使用二分查找法
            int i = 1;
            ulong total = 0;
            while (total < 2147483647)
            {
                total = Foo2(i);
                Console.WriteLine(total);
                i++;
            }
            Console.WriteLine(i);
            Console.ReadKey();
        }
        /// <summary>
        /// 二分查找法
        /// </summary>
        /// <param name="array"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private static int FibonacciSearch(int[] array, int key)
        {
            int length = array.Length;
            int low = 0, high = length - 1, mid = 0;
            mid = (low + high) / 2;
            while (mid < high)
            {
                if (array[mid] == key)
                {
                    break;
                }
                else if (array[mid] > key)
                {
                    high = mid;
                    mid = (low + high) / 2;
                }
                else if (array[mid] < key)
                {
                    low = mid;
                    mid = (low + high) / 2;
                }
            }
            return mid;
        }
    }
}

 

posted @ 2020-03-17 10:52  幸福安康  阅读(563)  评论(0编辑  收藏  举报