Search code examples
javamethodsfibonaccireturn-type

How can I return the FIbonacci sequence using an int return type method without using recursion?


I'm trying to create a method in Java that prints the fib series up to the number passed to the method. My issue is that I'm required to use an int return type to return the series and I cannot use recursion.

My First Idea

My original idea was like shown. Which works just fine. It takes an argument of type int and returns void simply printing the numbers as they are calculated.

public void fibonacci(int num) {
    int a = 0;
    int b = 0;
    int c = 1;
      

    for (int i = 0; i < num; i++) {
        a = b;
        b = c;
        c = a + b;
        System.out.print(c + ", ");
    }
}

What The Question Asks For

The code below shows what I was tasked to do. It asked for a method that takes an argument of type int and returns type int.

public int fibonacci(int num) {
   
    //some code...

    return x; //This is what confuses me. I know this isn't right.
}

To me this just seems impractical and maybe even impossible to use an int return type. I'm wondering if anyone knows a way this is possible.

Expected Output:

//Method call in driver class.
fibonacci(5);

//This would print to console.
1, 1, 2, 3, 5

Solution

  • You can use the equation [(h)^a - (j)^a] * [1/sqrt(5)].

    • 'a' is fibonacci number wanted
    • 'h' is [1 + sqrt(5)] / 2
    • 'j' is [1 - sqrt(5)] / 2
    public static int returnFibonacci(int a) {
    
      double firstTerm; // calculate h
    
      double secondTerm; //calculate j
    
      double fib; //calculate 1/sqrt(5) with firstTerm and secondTerm
    
    }