雷:面试时被问到fibonacci

本文介绍了两种实现斐波那契数列的方法:递归与非递归方式。递归方法通过调用自身来计算数值,而非递归方法采用循环结构逐步计算。文章提供了完整的代码示例。

1 1 2 3 5 8...

递归:

 

ExpandedBlockStart.gif代码
        static int FibonacciRecursive(int n)
        {        
            
if (n == 1 || n == 2)
                
return 1;
            
else if (n >= 2)
            {
                
return FibonacciRecursive(n - 1+ FibonacciRecursive(n - 2);
            }
            
else if (n <= 0)
            {
                
throw new ArgumentNullException(string.Format("{0} is illegal", n));              
            }
            
return 0;
        }

 

非递归:

 

ExpandedBlockStart.gif代码
        static int Fibonacci(int n)
        {
            
int lastNumber=1;
            
int secondNumber=1;
            
int currentNumber = 1;
            
if (n > 0)
            {
                
for (int i = 3; i <= n; i++)
                {                   
                    currentNumber 
= lastNumber+secondNumber;
                    secondNumber 
= lastNumber;
                    lastNumber 
= currentNumber;
                }
            }
            
else
            {
                
throw new ArgumentNullException(string.Format ("{0} is not a legal number",n));
            }
            
return currentNumber;
        }

 

 

转载于:https://www.cnblogs.com/qixue/archive/2010/02/20/1669632.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值