Fibonacci series : a series of numbers in which each number ( Fibonacci number ) is the sum of the two preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, 13,21,34 ,55,89 etc.
Solution1 using Recursion :
/**code to get nth fibonacci number **/
public static int fibonacciNumbers(int n){
if(n <= 0 || n == 1){
return 1;
} else {
return fibonacciNumbers(n-1) + fibonacciNumbers(n-2);
}
}
public static void main(String[] args){
int numberOfFibonacci = 15;
long start = System.currentTimeMillis();
java.util.List<Integer> fibnocList = new ArrayList<>();
for (int i = 0; i <= numberOfFibonacci; i++) {
fibnocList.add(fibonacciNumbers(i));
}
System.out.println(fibnocList);
long end = System.currentTimeMillis();
System.out.println("total time taken=" + (end -start) + " ms");
}
Output :
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]
total time taken=1 ms
Note : Till 40th element its able to print fibonacci numbers after that time of execution
increase exponentially.
Time complexity is O(n) & Space complexity O(n).
Solution2 using without Recursion :
/**printing the series of fibonacci number upto length n **/public static void fibonacciSeries(int n){int[] fibArray = new int[n];if(n < 0 ){System.out.println("invalid value");} else {for (int i = 0; i < n; i++) {if(i== 0 || i==1){fibArray[i] =1;} else {fibArray[i] = fibArray[i-1] + fibArray[i-2];}}}System.out.println("fibonacci number upto lenth n=" + n + " and series=" + Arrays.toString(fibArray));}public static void main(String[] args){long start = System.currentTimeMillis();fibonacciSeries(20);long end = System.currentTimeMillis();System.out.println("total time taken=" + (end -start) + " ms");}Note : Time complexity O(n) and space complexity is in place as using the arrays.
Output:fibonacci number upto lenth n=20 and series=[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144,233, 377, 610, 987, 1597, 2584, 4181, 6765]total time taken=0 ms
In both the solutions number 2 solutions is best possible solution with respect to time and space complexity.
Enjoy the code and enjoy the journey of Java!!!!
No comments:
Post a Comment