In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence:

By definition, the first two numbers in the Fibonacci sequence are 0 and 1, and each subsequent number is the sum of the previous two.

In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation

with seed values

Here is a simplest Java Program to generate Fibonacci Series.

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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
package crunchify.com.tutorials; import java.util.Scanner; /** * @author Crunchify.com * */ public class CrunchifyFibonacci { @SuppressWarnings("resource") public static void main(String args[]) { // input to print Fibonacci series upto how many numbers log("Enter number upto which Fibonacci series to print: "); int number = new Scanner(System.in).nextInt(); log("\nUsing Method-1: Using Recursion. Provided Number: " + number); // printing Fibonacci series upto number for (int i = 1; i <= number; i++) { log(fibonacciRecusion(i) + " "); } log("\nMethod-2: Fibonacci number at location " + number + " is ==> " + (fibonacciLoop(number) + "")); } // Method-1: Java program for Fibonacci number using recursion. public static int fibonacciRecusion(int number) { if (number == 1 || number == 2) { return 1; } return fibonacciRecusion(number - 1) + fibonacciRecusion(number - 2); // tail recursion } // Method-2: Java program for Fibonacci number using Loop. public static int fibonacciLoop(int number) { if (number == 1 || number == 2) { return 1; } int fibo1 = 1, fibo2 = 1, fibonacci = 1; for (int i = 3; i <= number; i++) { fibonacci = fibo1 + fibo2; // Fibonacci number is sum of previous two Fibonacci number fibo1 = fibo2; fibo2 = fibonacci; } return fibonacci; // Fibonacci number } private static void log(String number) { System.out.println(number); } } |

Output:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
Enter number upto which Fibonacci series to print: 10 Using Method-1: Using Recursion. Provided Number: 10 1 1 2 3 5 8 13 21 34 55 Method-2: Fibonacci number at location 10 is ==> 55 |

And there’s always:

public int fibonacci(int n) {

return (n<=1)? n:fibonacci(n-1)+fibonacci(n-2);

}