首页 > 技术文章 > 斐波那契递归和非递归俩种算法实例

cangqiongbingchen 2016-03-02 11:10 原文

package testcase;
/**
 * 
 * @decription
    \\
     \\_
  .---(')
o( )_-\_ 斐波那契递归和非递归俩种算法实例
 * @author bjliuzezhou
 * @date 2016年2月23日
 */
public class TypicalArithmetic_01 {
    
    public static void main(String[] args) {
        System.out.println(fn(6));
        System.out.println(noRecursion(6));
    }
    
    public static int fn(int n){
        if(n==0 | n==1)
            return 1;
        else
            return fn(n-1) + fn(n-2);
        
    }
    
    public static int noRecursion(int n){
        
        if(n==0 | n==1)
            return 1;
        else{
            int first = 1;
            int second = 1;
            int total = 0;
            for(int i=2; i<=n; i++){
                
                total = first + second;
                first = second;
                second = total;
            }
            
            return total;
        }
        
        
    }
}

 

推荐阅读