2016-05-21 7 views
0

フィボナッチの値を指定したインデックスまで印刷しようとしています。たとえば、インデックスが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; 
} 

} 

しかし、あなたはそれが再帰だ知っているように、それは私が唯一の指定したインデックスまで、すべてのインデックス値をプリントアウトできるように、私はそれを特定の方法を減らすことができ、すべての再帰的なcalls.Howを印刷するのか?

答えて

1

再帰フィボナッチの問題は、複雑さが指数関数的であることです。あなたはそれを反復的にしなければなりません、それは用語を印刷する方が簡単でしょう。

// 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; 
    } 
} 
+0

複雑さについての説明がベストです。 –

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; 

    } 

} 
+0

フィボナッチを使うことができない理由と繰り返しを使う方が良い理由について説明していないので、私はあなたにupvoteを与えています。もっと説明があり、非常にシンプルな前の答えを受け入れています。すてきな一日を! –

+0

あなたのupvoteと種類の願いに感謝します。良い一日を;あなたがまだ知りたいのなら、私がやったことをすべて説明することができます! –

関連する問題