📜  程序查找第N个奇数斐波那契数

📅  最后修改于: 2021-04-24 05:21:49             🧑  作者: Mango

给定整数N。任务是找到第N奇数斐波那契数。
斐波那契数列的奇数是:

例子:

Input: N = 3
Output: 3

Input: N = 4
Output: 5

方法:
仔细观察,可以推断出每三个斐波纳契数是偶数,因此第N奇数斐波那契数是一般斐波那契数列中的第{(3 * N + 1)/ 2}项。
下面是上述方法的实现:

C++
// C++ program for Nth odd fibonaci number
 
#include 
using namespace std;
 
// Function to find nth odd fibonaci number
int oddFib(int n)
{
    n = (3 * n + 1) / 2;
    int a = -1, b = 1, c, i;
    for (i = 1; i <= n; i++) {
        c = a + b;
        a = b;
        b = c;
    }
    return c;
}
 
// Driver Code
int main()
{
    int n = 4;
     
    cout << oddFib(n);
     
    return 0;
}


Java
// Java program for Nth odd fibonaci number
class GFG
{
     
    // Function to find nth odd fibonaci number
    static int oddFib(int n)
    {
        n = (3 * n + 1) / 2;
         
        int a = -1, b = 1, c = 0, i;
         
        for (i = 1; i <= n; i++)
        {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        int n = 4;
         
        System.out.println(oddFib(n));
    }
}
 
// This code is contributed by AnkitRai01


Python3
# Python3 program for Nth odd fibonaci number
 
# Function to find nth odd fibonaci number
def oddFib(n):
    n = (3 * n + 1) // 2
 
    a = -1
    b = 1
    c = 0
    for i in range(1, n + 1):
        c = a + b
        a = b
        b = c
 
    return c
 
# Driver Code
n = 4
 
print(oddFib(n))
 
# This code is contributed by mohit kumar


C#
// C# program for Nth odd fibonaci number
using System;
     
class GFG
{
     
    // Function to find nth odd fibonaci number
    static int oddFib(int n)
    {
        n = (3 * n + 1) / 2;
         
        int a = -1, b = 1, c = 0, i;
         
        for (i = 1; i <= n; i++)
        {
            c = a + b;
            a = b;
            b = c;
        }
        return c;
    }
     
    // Driver Code
    public static void Main (String[] args)
    {
        int n = 4;
         
        Console.WriteLine(oddFib(n));
    }
}
 
// This code is contributed by 29AjayKumar


Javascript


输出:
5

时间复杂度: O(N)