Find the next fibonacci number

Given a fibonacci number N, the task is to find the next fibonacci number.

Examples:

Input: N = 5
Output: 8
8 is the next fibonacci number after 5



Input: N = 3
Output: 5

Approach: The ratio of two adjacent numbers in the Fibonacci series rapidly approaches ((1 + sqrt(5)) / 2). So if N is multiplied by ((1 + sqrt(5)) / 2) and round it, the resultant number will be the next fibonacci number.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
  
// Function to return the next
// fibonacci number
int nextFibonacci(int n)
{
    double a = n * (1 + sqrt(5)) / 2.0;
    return round(a);
}
  
// Driver code
int main()
{
    int n = 5;
    cout << nextFibonacci(n);
}
  
// This code is contributed by mohit kumar 29

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach 
class GFG
{
      
    // Function to return the next
    // fibonacci number
    static long nextFibonacci(int n)
    {
        double a = n * (1 + Math.sqrt(5)) / 2.0;
        return Math.round(a);
    }
      
    // Driver code
    public static void main (String[] args)
    {
        int n = 5;
        System.out.println(nextFibonacci(n));
    }
}
  
// This code is contributed by AnkitRai01

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
from math import *
  
# Function to return the next 
# fibonacci number
def nextFibonacci(n):
    a = n*(1 + sqrt(5))/2.0
    return round(a)
  
# Driver code
n = 5
print(nextFibonacci(n))

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
  
class GFG 
{
      
    // Function to return the next
    // fibonacci number
    static long nextFibonacci(int n)
    {
        double a = n * (1 + Math.Sqrt(5)) / 2.0;
        return (long)Math.Round(a);
    }
      
    // Driver code
    public static void Main(String[] args)
    {
        int n = 5;
        Console.WriteLine(nextFibonacci(n));
    }
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

8


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.