Q9. Write a method to generate the nth Fibonacci number. Try both recursive and iterative function.
Fibonacci Function: f(0) = 0, f(1) = 1, f(n) = f(n - 1) + f(n - 2)
Answer:
public class Mathematics9 {
public static int fibonacciRecursive(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else if (n > 1) {
return fibonacciRecursive(n - 1) + fibonacciRecursive(n - 2);
} else {
// return error code to show that Fibonacci is not
// defined for given input
return -1;
}
}
public static int fibonacciIterative(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else if (n > 1) {
int tn_2 = 0;
int tn_1 = 1;
int tn = 0;
for (int i = 2; i <= n; i++) {
tn = tn_1 + tn_2;
tn_2 = tn_1;
tn_1 = tn;
}
return tn;
} else {
// return error code to show that Fibonacci is not
// defined for given input
return -1;
}
}
public static void main(String[] args) {
for (int i = 0; i <= 10; i++) {
System.out.print(fibonacciRecursive(i) + " ");
}
System.out.println();
for (int i = 0; i <= 10; i++) {
System.out.print(fibonacciIterative(i) + " ");
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.