Register a free account to unlock additional features at BleepingComputer.com
Welcome to BleepingComputer, a free community where people like yourself come together to discuss and learn how to use their computers. Using the site is easy and fun. As a guest, you can browse and view the various discussions in the forums, but can not create a new topic or reply to an existing one unless you are logged in. Other benefits of registering an account are subscribing to topics and forums, creating a blog, and having no ads shown anywhere on the site.


Click here to Register a free account now! or read our Welcome Guide to learn how to use this site.

Generic User Avatar

Fibonacci function result confusion


  • Please log in to reply
1 reply to this topic

#1 trivedi10

trivedi10

  •  Avatar image
  • Members
  • 2 posts
  • OFFLINE
  •  
  • Local time:02:14 AM

Posted 20 June 2022 - 06:10 AM

public class Fibonacci {
    public static long fib(int n) {
        if (n <= 1) return n;
        else return fib(n-1) + fib(n-2);
    }


    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        for (int i = 1; i <= N; i++)
            System.out.println(i + ": " + fib(i));
    }
}
Let's assume that the user input "java Fibonacci 7", so the result would be like this:
 
1: 1
2: 1
3: 2
4: 3
5: 5
6: 8
7: 13
 
I seem to be totally confused with how this works, starting with argument 3. When the fib(i) method gets passed 3, shouldn't it return 3 as well since if n = 3 then the sum of fib(n-1) /n-1 is 2/ and fib(n-2) /n-2 is 1/ is 3. And so on the other numbers forward.


BC AdBot (Login to Remove)

 


#2 trivedi10

trivedi10
  • Topic Starter

  •  Avatar image
  • Members
  • 2 posts
  • OFFLINE
  •  
  • Local time:02:14 AM

Posted 20 June 2022 - 06:14 AM

The Fibonacci series either starts with zero or with 1, non of which options has the 3 as the third number.
 
1 1 2 3 5 ...


0 1 1 2 3 5 8 ...
The usual way is to have the second option but starting at index 0 so that fib(0) = 0, fib(1) = fib(2) = 1
 
Reference - Quora, Scaler
 
Please correct me to clarify.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users