Search code examples
javafibonacci

Fibonacci sequence without using Array


I am trying to practice JAVA by coding a Fibonacci sequence in which the user can declare the length of the Fibonacci starting from 0 to n. Here is my code:

public class test {
public static void main(String args[]) throws IOException {
    BufferedReader pao = new BufferedReader(
            new InputStreamReader(System.in));

    System.out.print("Enter number: ");
    String enter = pao.readLine();
    int ent = Integer.parseInt(enter);

    int total1 = 0;
    int total2 = 1;
    int total3 = 0;

    for (int a = 0; a < ent; a++) {
        if (a <= 1) {
            System.out.print(" " + total3);
            total3 = total1 + total2;

        } else if (a == 2) {
            System.out.print(" " + total3);
        } else {
            total1 = total2;
            total2 = total3;
            total3 = total1 + total2;
            System.out.print(" " + total3);

        }
    }

}
}  

Is there another way to do this in a much more simpler, shorter and "Nicer" way? still without using arrays. Thank you in advance.


Solution

  • You can use recursive fibonacci but it will increase your runtime from O(n) to O(2^n) it's like bellow

    int fib(int n) {
       if (n <= 1)
          return n;
       return fib(n-1) + fib(n-2);
    }
    

    and there is another way that decrease your runtime to O(log n) but it use arrays (Using power of the matrix {{1,1},{1,0}}) you can read about it here. also for above recursion if you use array you can change runtime to O(n) again by method call dynamic programming.