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