---
title: "面试题之Fibonacci数列"
author: "eyeName"
date: "2011-06-16T18:14:43Z"
tags: []
categories: ["编程语言"]
slug: "fibonacci"
draft: false
lastmod: "2011-06-16T18:14:43Z"
id: 1095301
url: "https://eyename.iteye.com/blog/1095301"
---

求Fibonacci数列：1,1,2,3,5,8.....第40个数的值数列满足递推公式
* F1=1,F2=1     Fn=Fn-1+Fn-2(n>2)

public class Feb {

public static void main(String args) {

   System.out.println(f(40));
   System.out.println(f1(40)); 
}

//非递归方法
public static long f(long index)
{
   if(index<1)
   {
    System.out.println("invalid parameter!");
      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;
}

//递归方法
public static long f1(long index)
{
   if(index<1)
   {
    System.out.println("invalid parameter!");
    return -1;
   }
   if(index==1 || index==2)
   {
    return 1;
   }else
   {
    return f1(index-1)+f1(index-2);
   }
}

}