1 1 2 3 5 8 11 19......

求1 1 2 3 5 8 11 19......第n个数

递归算法和循环算法的实现

        private void frmMain_Load(object sender, EventArgs e)
        {

            //int result = this.FindSum(5);
            //MessageBox.Show(result.ToString());//输出5
            //
            int key = 0;
            int result;

            while (true)
            {
                result = this.RegFindValue(4)+this.RegFindValue(3);//递归算法的调用
                MessageBox.Show(result.ToString());//连续输出五次5
                key++;
                if (key==5)                
                    break;
                
            }
                    
       
            //MessageBox.Show(result.ToString());
            //循环算法的调用
            int value = LoopFindValue(6);
            MessageBox.Show(value.ToString());


        }

        //递归算法的实现
        private int RegFindValue(int m)
        {
            if (m == 1 || m == 2)
                return 1;
            else
                return RegFindValue(m - 1) + RegFindValue(m - 2);
        }


        //循环算法的实现
        private int LoopFindValue(int n)
        {
            if (n<=1)            
                return 0;
                
            
            int result=0;
            int firstnum = 0, secondnum = 0;
            for (int i = 1; i <=n; i++)
            {
                if (i == 1 || i == 2)
                    result=firstnum = secondnum = 1;
                else
                {
                    result = firstnum + secondnum;
                    firstnum = secondnum;
                    secondnum = result;
 
                    
                }
                             
            }
            return result;
        }

      

        
    

  

posted @ 2013-03-27 06:33  Predator  阅读(293)  评论(0编辑  收藏  举报