The Fibonacci sequence is a set of Numbers where each number, after the first two, is the sum of the previous two numbers, resulting in the following sequence:
0 1 1 2 3 5 6 13 21 34 55 89 144 233 377 610 987 1597 2584 4181
How can I write a method, using recursion, which will return a specified fibonacci number? I want to avoid using an array
Here is what i have so far
public static int fibo(int n)
{
if (n==1)
return 1;
else
return //this is the part i am stuck on
As a certain fibonacci number (except 1) is on its percursor you call:
public static int fibo(int n) {
if (n < 0) {
throw new IndexOutOfBoundsException("Can't calculate fibonacci number for negative index");
} else if(n == 0 || n == 1) {
return n;
}
return fibo(n-1) + fibo(n-2);
}
public static int fibo(int n){
if(n<=2)
return (n-1);
else
return fibo(n-1) + fibo(n-2);
}
Each fibonacci number is the sum of its 2 predecessors. You can't just have a base case of n=1 since when calculating n = 2 you will find it is the sum of n = 1 and n = 0? which would not be defined.
Note: This is assuming you are 1-indexing the list of fib numbers ie 0 is the first 1 the second then 1 the third etc.
public class Fibonacci
{
public static int fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args)
{
System.out.println(fibonacci(11));
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.