非遞歸算法計算1+1+2+3+5+8+....加到第40個數字

package com58.bj.java;

public class Fab {

	/**
	 * @param args
	 * 非遞歸算法計算1+1+2+3+5+8+....加到第40個數字
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(f(40));

	}

	public static long f(int index) {
		// TODO Auto-generated method stub
		if(index < 1)
		{
			System.out.println("invalid paramter!");
			return -1;
		}
		if(index ==1 || index ==2){
			return 1;
		}
		long f1 = 1L;
		long f2 = 1L;
		long f = 0;
		for(int i=0;i<index-2;i++){
			f = f1 + f2 ;
			f1 = f2;
			f2 = f;
		}
		return f;
	}

}
相關文章
相關標籤/搜索