Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

40 lines
1.0 KiB

  1. The Fibonacci Sequence is a series of numbers where the next number is found by
  2. adding the previous two numbers.
  3. Ex:
  4. | n | 1 | 2 | 3 | 4 | 5 | 6 |
  5. |---|---|---|---|---|---|---|
  6. | x | 1 | 1 | 2 | 3 | 5 | 8 |
  7. ```
  8. class Fibonacci
  9. {
  10.    public static void main(String[] args)
  11.    {
  12.        for(int i = 1; i < 60; i ++)
  13.        {
  14.                System.out.println("Fibonacci " + i + " is: t" + fib(i));
  15.        }
  16.    }
  17. //recursive definition of Fibonacci
  18.    public static double fib(int n)
  19.    {
  20.        if(n == 1 \|\| n == 2)
  21.        {
  22.            return(1);
  23.        }
  24.        return(fib(n -1) + fib(n -2));
  25.    }
  26. }
  27. ```
  28. ![](media/088cc48e754c1b99e0fcd5a5eddb9d64.png)
  29. I would like to note that solving each Fibonacci number recursively is not
  30. efficient due to the enormous stack it creates for higher elements. A more
  31. effective way to calculate the Fibonacci sequence is iteratively. I only did
  32. this recursively to demonstrate its recursive nature.