Problem 1: Fibonacci Sequence
The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones, usually starting with 0 and 1.
This is an interesting problem in the field of dynamic programming because the Fibonacci sequence can be efficiently calculated using dynamic programming techniques.
Let's take a look at how we can solve the Fibonacci sequence problem using dynamic programming. Here's the Java code that calculates the Fibonacci number at a given position n
using dynamic programming:
1public class Fibonacci {
2
3 public static int fibonacci(int n) {
4 // base cases
5 if (n == 0) {
6 return 0;
7 }
8 if (n == 1) {
9 return 1;
10 }
11 // array to store fibonacci values
12 int[] fib = new int[n + 1];
13 fib[0] = 0;
14 fib[1] = 1;
15 // compute fibonacci sequence
16 for (int i = 2; i <= n; i++) {
17 fib[i] = fib[i - 1] + fib[i - 2];
18 }
19 // return the fibonacci number at position n
20 return fib[n];
21 }
22
23 public static void main(String[] args) {
24 int n = 10;
25 int fibValue = fibonacci(n);
26 System.out.println("The fibonacci value at position " + n + " is: " + fibValue);
27 }
28}
In this code, we define a fibonacci
method that takes an integer n
as input and returns the Fibonacci number at that position using dynamic programming.
The method first handles the base cases where n
is 0 or 1, and then creates an array fib
to store the Fibonacci values. We initialize the first two values of the array with 0 and 1, and then use a loop to compute the remaining Fibonacci values. Finally, we return the Fibonacci value at position n
.
To test the code, we can call the fibonacci
method with a value of n
and print the result. For example, in the main
method, we set n
to 10 and print the Fibonacci value at position 10.
Feel free to modify the code and test it with different values of n
to see the Fibonacci sequence in action!
xxxxxxxxxx
public class Fibonacci {
public static int fibonacci(int n) {
// base cases
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
// array to store fibonacci values
int[] fib = new int[n + 1];
fib[0] = 0;
fib[1] = 1;
// compute fibonacci sequence
for (int i = 2; i <= n; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
// return the fibonacci number at position n
return fib[n];
}
public static void main(String[] args) {
int n = 10;
int fibValue = fibonacci(n);
System.out.println("The fibonacci value at position " + n + " is: " + fibValue);
}
}