What is fibonacci series
The Fibonacci series is a series of elements where, the previous two elements are added to get the next element, starting with 0 and 1.
Example of the fibonacci series of a given number N.
1 2 3 4 5 6 |
Input :N=10 Output:0 1 1 2 3 5 8 13 21 34 Here first term of Fibonacci is 0 and second is 1, so that 3rd term = first(o) + second(1) etc and so on. Input N=15 Output:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
Fibonacci series program in java
Fibonacci series logic in java,first set number1 values 0 and number2 value 1, print the number1 and number1 on screen, then set the sum of number1 and number2 as the next number3, after print number3,set the number1 value as number2,and set the number2 value as number3,then go to next loop.
1)By using Loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
// Java program for the above approach class GFG { // Function to print N Fibonacci Number static void Fibonacci(int N) { int num1 = 0, num2 = 1; int counter = 0; // Iterate till counter is N while (counter < N) { // Print the number System.out.print(num1 + " "); // Swap int num3 = num2 + num1; num1 = num2; num2 = num3; counter = counter + 1; } } // Driver Code public static void main(String args[]) { // Given Number N int N = 10; // Function Call Fibonacci(N); } } |
2)By using Recursive
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// Recursive implementation of // Fibonacci Series class GFG { // Function to print the fibonacci series static int fib(int n) { // Base Case if (n <= 1) return n; // Recursive call return fib(n - 1) + fib(n - 2); } // Driver Code public static void main(String args[]) { // Given Number N int N = 10; // Print the first N numbers for (int i = 0; i < N; i++) { System.out.print(fib(i) + " "); } } } |
3)By using dynamic programming
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
// Dynamic Programming approach for // Fibonacci Series class fibonacci { // Function to find the fibonacci Series static int fib(int n) { // Declare an array to store // Fibonacci numbers. // 1 extra to handle case, n = 0 int f[] = new int[n + 2]; int i; // 0th and 1st number of // the series are 0 and 1 f[0] = 0; f[1] = 1; for (i = 2; i <= n; i++) { // Add the previous 2 numbers // in the series and store it f[i] = f[i - 1] + f[i - 2]; } // Nth Fibonacci Number return f[n]; } public static void main(String args[]) { // Given Number N int N = 10; // Print first 10 term for (int i = 0; i < N; i++) System.out.print(fib(i) + " "); } } |
output
1 |
0 1 1 2 3 5 8 13 21 34 |
Refer:Fibonacci_number