Find the previous fibonacci number

Given aFibonacci number N , the task is to find the previous Fibonacci number.

Examples:

Input:N = 8

Output:5

5 is the previous fibonacci number before 8.

Input:N = 5

Output:3

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Approach: The ratio of two adjacent numbers in the Fibonacci series rapidly approaches ((1 + sqrt(5)) / 2) . So if N is divided by ((1 + sqrt(5)) / 2) and then rounded, the resultant number will be the previous 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 previous
// fibonacci number
int previousFibonacci( int n)
{
   double a = n / ((1 + sqrt (5)) / 2.0);
   return round(a);
}
 
// Driver code
int main()
{
   int n = 8;
   cout << (previousFibonacci(n));
}
 
// This code is contributed by Mohit Kumar

chevron_right

filter_none

Python3

filter_none

edit

close

play_arrow

link

brightness_4

code

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

chevron_right

filter_none

C#

filter_none

edit

close

play_arrow

link

brightness_4

code

// C# implementation of the approach
using System;
 
class GFG
{
   
// Function to return the previous
// fibonacci number
static int previousFibonacci( int n)
{
   double a = n / ((1 + Math.Sqrt(5)) / 2.0);
   return ( int )Math.Round(a);
}
 
// Driver code
public static void Main()
{
   int n = 8;
   Console.Write(previousFibonacci(n));
}
}
 
// This code is contributed by Akanksha_Rai

chevron_right

filter_none

Output:

My Personal Notes arrow_drop_up

  
  
 

spp____

Check out this Author'scontributed 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.

Improved By : mohit kumar 29

我来评几句
登录后评论

已发表评论数()

相关站点

+订阅
热门文章