Find the previous fibonacci number

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++
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;// Function to return the previous// fibonacci numberint previousFibonacci(int n){ double a = n / ((1 + sqrt(5)) / 2.0); return round(a);}// Driver codeint main(){ int n = 8; cout << (previousFibonacci(n));}// This code is contributed by Mohit Kumar |
Java
// Java implementation of the approachimport java.io.*;class GFG{ // Function to return the previous// fibonacci numberstatic int previousFibonacci(int n){ double a = n / ((1 + Math.sqrt(5)) / 2.0); return (int)Math.round(a);}// Driver codepublic static void main (String[] args) { int n = 8; System.out.println(previousFibonacci(n));}}// This code is contributed by ajit. |
Python3
# 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 = 8print(previousFibonacci(n)) |
C#
// C# implementation of the approachusing System;class GFG{ // Function to return the previous// fibonacci numberstatic int previousFibonacci(int n){ double a = n / ((1 + Math.Sqrt(5)) / 2.0); return (int)Math.Round(a);}// Driver codepublic static void Main(){ int n = 8; Console.Write(previousFibonacci(n));}}// This code is contributed by Akanksha_Rai |
Javascript
<script>// Javascript implementation of the approach// Function to return the previous// fibonacci numberfunction previousFibonacci(n){ var a = n / ((1 + Math.sqrt(5)) / 2); return Math.round(a);}// Driver codevar n = 8;document.write(previousFibonacci(n));// This code is contributed by rutvik_56.</script> |
Output:
5
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



