If the fibonacci coudl be used for breading of rabbits and used recursion how wo
ID: 674858 • Letter: I
Question
If the fibonacci coudl be used for breading of rabbits and used recursion how would the program look?
After breading the rabbit takes 1 month to reach adult hood and start breading, 1 month to give borth then they die after 4 months. Show recursion formula for the number of rabbits in the time of N.
public class Fibonacci { public static long fibo(int n) {
long[] f = new long[n+1]; f[1] = 1;
for (int i=2; i<=n; i++)
f[i] = f[i-1] + f[i-2]; return f[n]; }
public static void main(String[] args)
{ int N = Integer.parseInt(args[0]); StdOut.println(N + ": " + fibo(N)); } }
Explanation / Answer
Answer :
The below is the sequence of numbers is known as Fibonacci numbers.
0, 1, 1, 2, 3, 5, 8, 13, 21 ....
To obtain the numbers, we start with 0 and 1 after which every number is the sum of the previous two numbers.
For example, the first two numbers will be 0 and 1
0, 1
To obtain the next number, we add the previous two numbers i.e 0 and 1 which gives 1.
0, 1, 1
The next number would be 1 + 1 = 2
0, 1, 1, 2
The next number would be 1 + 2 = 3
0, 1, 1, 2, 3
On proceeding like this gives the Fibonacci numbers. A particular term in the series is represented as Fn where n is the position of that number from the beginning. For example, F0 = 0, F1 = 1, F2 = 1, F3=2, F4 = 3, F5 = 5 and so on...
The Fibonacci series can be expressed as a recurrence relation as shown below:
F0 = 0F1 = 1
Fn = Fn-1 + Fn-2 ; n>=2
Below is the program re-written with small changes in java :
import java.util.*;
class Fibonacci
{
public static long fibo(int n)
{
long[] f = new long[n+1];
f[1] = 1;
for (int i=2; i<=n; i++)
f[i] = f[i-1] + f[i-2];
return f[n];
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter The Number Of Rabbits :");
int N=sc.nextInt();
// int N = Integer.parseInt(args[0]); //N value taken by the input given by user replaced in above line
// StdOut.println(N + ": " + fibo(N)); //System.out.println is used to print in java replaced in below line
System.out.println("Time To Reach Adulthood is (N) "+ ": "+ fibo(N)+" months");
}
}