За дадена стойност n намерете n-тото четно Числото на Фибоначи .
Примери:
Вход n = 3
Изход 34
Обяснение Първите 3 четни числа на Фибоначи са 0 2 8 34 144, като 3-то е 34.Вход n = 4
Изход 144
Обяснение Първите 4 четни числа на Фибоначи са 0 2 8 34 144, като 4-то е 144.
[Наивен подход] Проверете едно по едно всяко число на Фибоначи
Ние генерира всички числа на Фибоначи и проверете всяко число едно по едно дали е някога или не
[Ефективен подход] Използване на директна формула - O(n) време и O(1) пространство
Поредицата от четни числа на Фибоначи е 0 2 8 34 144 610 2584.... От тази последователност можем да добием представа, че всяко трето число в редицата е четно и последователността следва следната рекурсивна формула.
Повторението за четната последователност на Фибоначи е:
Eefn = 4fn-1 + Efn-2
Как работи горната формула?
Нека да разгледаме оригиналната формула на Фибоначи и да я запишем под формата на Fn-3 и Fn-6 поради факта, че всяко трето число на Фибоначи е четно.
Fn = Fn-1 + Fn-2 [Разширяване на двата термина]
= Fn-2 + Fn-3 + Fn-3 + Fn-4
= Fn-2 + 2Fn-3 + Fn-4 [Разширяване на първия член]
= Fn-3 + Fn-4 + 2Fn-3 + Fn-4
= 3Fn-3 + 2Fn-4 [Разширяване на едно Fn-4]
= 3Fn-3 + Fn-4 + Fn-5 + Fn-6 [Смесване на Fn-4 и Fn-5]
= 4Fn-3 + Fn-6
Тъй като всяко трето число на Фибоначи е четно, така че ако Fn е
дори тогава Fn-3 е четен и Fn-6 също е четен. Нека Fn е
x-ти четен елемент и го маркирайте като EFx.
основна програма в javaАко Fn е EFx, тогава Fn-3 е предишното четно число, т.е. EFx-1
и Fn-6 е предшестващ EFx-1, т.е. EFx-2
Така че Fn = 4Fn-3 + Fn-6
което означава
EFx = 4EFx-1 + EFx-2
По-долу е проста реализация на идеята
C++#include using namespace std; // Optimized function to calculate the nth // even Fibonacci number int nthEvenFibonacci(int n) { // Base case: the first even Fibonacci number is 2 if (n == 1) return 2; // Start with the first two even Fibonacci numbers int prev = 0; // F(0) int curr = 2; // F(3) // We need to find the nth even Fibonacci number for (int i = 2; i <= n; i++) { // Next even Fibonacci number is 4 times // the previous even Fibonacci number plus // the one before that int nextEvenFib = 4 * curr + prev; prev = curr; curr = nextEvenFib; } return curr; } int main() { int n = 2; int result = nthEvenFibonacci(n); cout << result << endl; return 0; }
Java public class GfG { // Function to calculate the nth even Fibonacci // number using dynamic programming public static int nthEvenFibonacci(int n) { // Base case: the first even // Fibonacci number is 2 if (n == 1) return 2; // Start with the first two Fibonacci // numbers (even ones) int prev = 0; // F(0) int curr = 2; // F(3) // We need to find the nth even Fibonacci number for (int i = 2; i <= n; i++) { // Next even Fibonacci number is 4 // times the previous even Fibonacci // number plus the one before that int nextEvenFib = 4 * curr + prev; prev = curr; curr = nextEvenFib; } return curr; } public static void main(String[] args) { int n = 2; int result = nthEvenFibonacci(n); System.out.println(result); } }
Python # Function to calculate the nth even # Fibonacci number using dynamic programming def nthEvenFibonacci(n): # Base case: the first even Fibonacci number is 2 if n == 1: return 2 # Start with the first two Fibonacci numbers (even ones) prev = 0 # F(0) curr = 2 # F(3) # We need to find the nth even Fibonacci number for i in range(2 n + 1): # Next even Fibonacci number is 4 times the # previous even Fibonacci number plus the # one before that next_even_fib = 4 * curr + prev prev = curr curr = next_even_fib return curr # Driver code if __name__ == '__main__': n = 2 # Setting n to 2 result = nthEvenFibonacci(n) print(result)
C# using System; class GfG { // Function to calculate the nth even Fibonacci // number using dynamic programming public int NthEvenFibonacci(int n) { // Base case: the first even Fibonacci number is 2 if (n == 1) return 2; // Start with the first two Fibonacci numbers (even ones) int prev = 0; // F(0) int curr = 2; // F(3) // We need to find the nth even Fibonacci number for (int i = 2; i <= n; i++) { // Next even Fibonacci number is 4 times the // previous even Fibonacci number plus the // one before that int nextEvenFib = 4 * curr + prev; prev = curr; curr = nextEvenFib; } return curr; } static void Main() { GfG gfg = new GfG(); int n = 2; int result = gfg.NthEvenFibonacci(n); Console.WriteLine(result); // Output: The nth even Fibonacci number } }
JavaScript // Function to calculate the nth even Fibonacci number using dynamic programming function nthEvenFibonacci(n) { // Base case: the first even Fibonacci number is 2 if (n === 1) return 2; // Start with the first two Fibonacci numbers (even ones) let prev = 0; // F(0) let curr = 2; // F(3) // We need to find the nth even Fibonacci number for (let i = 2; i <= n; i++) { // Next even Fibonacci number is 4 times // the previous even Fibonacci number plus // the one before that let nextEvenFib = 4 * curr + prev; prev = curr; curr = nextEvenFib; } return curr; } // Example usage: const n = 2; // Setting n to 2 const result = nthEvenFibonacci(n); console.log(result);
Изход
8