user6232985
user6232985

Reputation:

How can I return every index value up until given index in Fibonacci

I'm trying to print all Fibonacci values up until my given index.So for example if my index is 5, it should print 0,1,1,2,3,5. I tried the following:

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;
}

}

However, as you know it's recursion,it's printing all recursive calls.How can I reduce it a certain way so that I can only printout all index values up until the given index?

Upvotes: 0

Views: 44

Answers (2)

Nadim Baraky
Nadim Baraky

Reputation: 457

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;

  }

}

Upvotes: 0

T. Claverie
T. Claverie

Reputation: 12256

The problem with recursive Fibonacci is that the complexity is exponential. You have to make it iterative, it will be easier to print the terms.

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

Upvotes: 1

Related Questions