给定一个值n,找到第n个偶数斐波那契数。
例子 :
Input : n = 3
Output : 34
Input : n = 4
Output : 144
Input : n = 7
Output : 10946
斐波那契数是以下整数序列中的数字。
0、1、1、2、3、5、8、13、21、34、55、89、144等。
其中按顺序给出任何数字:
Fn = Fn-1 + Fn-2
with seed values
F0 = 0 and F1 = 1.
偶数斐波那契数列是0、2、8、34、144、610、2584…。我们需要按此顺序找到第n个数字。
如果我们仔细研究斐波那契数列,我们会注意到序列中的第三个数字都是偶数,偶数序列遵循以下递归公式。
Recurrence for Even Fibonacci sequence is:
EFn = 4EFn-1 + EFn-2
with seed values
EF0 = 0 and EF1 = 2.
EFn represents n'th term in Even Fibonacci sequence.
以上公式如何运作?
让我们看一下原始的斐波那契公式,并以Fn-3和Fn-6的形式编写它,因为事实上每三个斐波那契数都是偶数。
Fn = Fn-1 + Fn-2 [Expanding both terms]
= Fn-2 + Fn-3 + Fn-3 + Fn-4
= Fn-2 + 2Fn-3 + Fn-4 [Expending first term]
= Fn-3 + Fn-4 + 2Fn-3 + Fn-4
= 3Fn-3 + 2Fn-4 [Expending one Fn-4]
= 3Fn-3 + Fn-4 + Fn-5 + Fn-6 [Combing Fn-4 and Fn-5]
= 4Fn-3 + Fn-6
Since every third Fibonacci Number is even, So if Fn is
even then Fn-3 is even and Fn-6 is also even. Let Fn be
xth even element and mark it as EFx.
If Fn is EFx, then Fn-3 is previous even number i.e. EFx-1
and Fn-6 is previous of EFx-1 i.e. EFx-2
So
Fn = 4Fn-3 + Fn-6
which means,
EFx = 4EFx-1 + EFx-2
C++
// C++ code to find Even Fibonacci
//Series using normal Recursion
#include
using namespace std;
// Function which return
//nth even fibonnaci number
long int evenFib(int n)
{
if (n < 1)
return n;
if (n == 1)
return 2;
// calculation of
// Fn = 4*(Fn-1) + Fn-2
return ((4 * evenFib(n-1)) +
evenFib(n-2));
}
// Driver Code
int main ()
{
int n = 7;
cout << evenFib(n);
return 0;
}
Java
// Java code to find Even Fibonacci
// Series using normal Recursion
class GFG{
// Function which return
// nth even fibonnaci number
static long evenFib(int n)
{
if (n < 1)
return n;
if (n == 1)
return 2;
// calculation of
// Fn = 4*(Fn-1) + Fn-2
return ((4 * evenFib(n-1)) +
evenFib(n-2));
}
// Driver Code
public static void main (String[] args)
{
int n = 7;
System.out.println(evenFib(n));
}
}
// This code is contributed by
// Smitha Dinesh Semwal
Python3
# Python3 code to find Even Fibonacci
# Series using normal Recursion
# Function which return
#nth even fibonnaci number
def evenFib(n) :
if (n < 1) :
return n
if (n == 1) :
return 2
# calculation of
# Fn = 4*(Fn-1) + Fn-2
return ((4 * evenFib(n-1)) + evenFib(n-2))
# Driver Code
n = 7
print(evenFib(n))
# This code is contributed by Nikita Tiwari.
C#
// C# code to find Even Fibonacci
// Series using normal Recursion
using System;
class GFG {
// Function which return
// nth even fibonnaci number
static long evenFib(int n)
{
if (n < 1)
return n;
if (n == 1)
return 2;
// calculation of Fn = 4*(Fn-1) + Fn-2
return ((4 * evenFib(n - 1)) +
evenFib(n - 2));
}
// Driver code
public static void Main ()
{
int n = 7;
Console.Write(evenFib(n));
}
}
// This code is contributed by Nitin Mittal.
PHP
Javascript
输出 :
10946