Find the previous fibonacci number
Last Updated :
10 Mar, 2022
Given a Fibonacci 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
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++
#include <bits/stdc++.h>
using namespace std;
int previousFibonacci( int n)
{
double a = n / ((1 + sqrt (5)) / 2.0);
return round(a);
}
int main()
{
int n = 8;
cout << (previousFibonacci(n));
}
|
Java
import java.io.*;
class GFG
{
static int previousFibonacci( int n)
{
double a = n / (( 1 + Math.sqrt( 5 )) / 2.0 );
return ( int )Math.round(a);
}
public static void main (String[] args)
{
int n = 8 ;
System.out.println(previousFibonacci(n));
}
}
|
Python3
from math import *
def previousFibonacci(n):
a = n / (( 1 + sqrt( 5 )) / 2.0 )
return round (a)
n = 8
print (previousFibonacci(n))
|
C#
using System;
class GFG
{
static int previousFibonacci( int n)
{
double a = n / ((1 + Math.Sqrt(5)) / 2.0);
return ( int )Math.Round(a);
}
public static void Main()
{
int n = 8;
Console.Write(previousFibonacci(n));
}
}
|
Javascript
<script>
function previousFibonacci(n)
{
var a = n / ((1 + Math.sqrt(5)) / 2);
return Math.round(a);
}
var n = 8;
document.write(previousFibonacci(n));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...