给定斐波那契数N ,任务是找到先前的斐波那契数。
例子:
Input: N = 8
Output: 5
5 is the previous fibonacci number before 8.
Input: N = 5
Output: 3
方法:斐波那契数列中两个相邻数字的比值迅速接近((1 + sqrt(5))/ 2) 。因此,如果将N除以(((1 + sqrt(5))/ 2))然后四舍五入,则结果数将是先前的斐波那契数。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
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
Java
// Java implementation of the approach
import java.io.*;
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 (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 = 8
print(previousFibonacci(n))
C#
// 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
Javascript
输出:
5