Генерация рядов Фибоначчи в Java: методы рекурсии, массива и переменных

Вот пример того, как сгенерировать ряд Фибоначчи в Java с использованием различных методов:

Метод 1: использование рекурсии

public class FibonacciSeries {
    public static int fibonacci(int n) {
        if (n <= 1)
            return n;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }
    public static void main(String[] args) {
        int n = 10; // Change the value of n to generate the desired number of terms
        for (int i = 0; i < n; i++) {
            System.out.print(fibonacci(i) + " ");
        }
    }
}

Метод 2. Использование массива

public class FibonacciSeries {
    public static void main(String[] args) {
        int n = 10; // Change the value of n to generate the desired number of terms
        int[] fibonacci = new int[n];
        fibonacci[0] = 0;
        fibonacci[1] = 1;
        for (int i = 2; i < n; i++) {
            fibonacci[i] = fibonacci[i - 1] + fibonacci[i - 2];
        }
        for (int i = 0; i < n; i++) {
            System.out.print(fibonacci[i] + " ");
        }
    }
}

Метод 3: использование переменных

public class FibonacciSeries {
    public static void main(String[] args) {
        int n = 10; // Change the value of n to generate the desired number of terms
        int firstTerm = 0;
        int secondTerm = 1;
        System.out.print(firstTerm + " " + secondTerm + " ");
        for (int i = 3; i <= n; i++) {
            int nextTerm = firstTerm + secondTerm;
            System.out.print(nextTerm + " ");
            firstTerm = secondTerm;
            secondTerm = nextTerm;
        }
    }
}