如何在Fibonacci中给定索引之前返回每个索引值

时间:2016-05-21 07:03:48

标签: java recursion

我正在尝试打印所有Fibonacci值直到我给定的索引。例如,如果我的索引是5,它应该打印0,1,1,2,3,5。我尝试了以下方法:

public class FibPrac5202016
{
   static ArrayList <Long> list = new ArrayList<Long>();
public static void main(String [] args)  {
    Scanner input = new Scanner(System.in);
    System.out.println("Enter index number: ");
    int integer = input.nextInt();
  FibPrac5202016 object = new FibPrac5202016();

System.out.println(object.operation(integer));
System.out.println(list.toString());
}

public static long operation(long n) {

     long number =0;
 if(n==0)
     number= 0;
 if(n==1)
     number = 1;
 try {
     if( n < 0)
     throw new Exception("Positive Number Required");

 }
 catch(Exception exc)
 {
     System.out.println("Error: " + exc.getMessage());
   System.exit(0);
 }
   if(n >1) {
  number = operation((n-1))+ operation((n-2));
   list.add(number);
}
   return number;
}

}

然而,正如你所知它的递归,它打印所有递归调用。如何以某种方式减少它,以便我只能打印出所有索引值,直到给定的索引?

2 个答案:

答案 0 :(得分:1)

递归Fibonacci的问题在于复杂性是指数级的。你必须使它迭代,打印术语会更容易。

// Compute the terms of fibonacci up to n
public static void operation(long n) {
    long a = 0;
    long b = 1;
    while (a <= n) {
        System.out.println(a);
        b = a+b;
        a = b-a;
    }
}

答案 1 :(得分:0)

import java.util.Scanner;

//this program prints up to i-th Fibonacci number; 
//done by Nadim Baraky

public class Fibonacci {

  public static void main(String[] args) {
     //declare and initialize three int variables 
     int a = 0, b = 0, c = 1;

     Scanner sc = new Scanner(System.in); 

     System.out.print("Enter index number: ");
     int i = sc.nextInt(); 

     sc.close(); //close the scanner object

     System.out.print(a + ",");

     //this loop does the flipping and addition 
     for(int n=1;n<=i-1;n++) {
        a = b; //set the variable a to have the value of b
        b = c; //set the variable b to have the value of c
        c = a + b; //set c to have the sum of a and b;
        System.out.print(b + ","); //prints up to the index entered;
     }

      System.out.print(c + "."); //prints the number at index i;

  }

}