Recursion: Fibonacci Numbers

  • + 0 comments

    Here was my idea which is similar, but easier to read/remember because it's more mechanical--the modulo math is removed, and instead an extra copy operation is used to keep the array ordered newest-to-oldest. Special case 0 and start the loop at 1.

    public static int Fibonacci(int n) {
            if (n == 0) {
                return 0;
            }
            
            int[] answers = new int[] { 0, 1 };
            for (int ii = 1; ii < n; ii++) {
                answers[1] = answers[0] + (answers[0] = answers[1]);
            }
            return answers[1];
        }