Find Index of given fibonacci number in constant time
Last Updated :
26 Oct, 2023
We are given a Fibonacci number. The first few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .....
We have to find the index of the given Fibonacci number, i.e. like Fibonacci number 8 is at index 6.
Examples :
Input : 13
Output : 7
Input : 34
Output : 9
Method 1 (Simple) : A simple approach is to find Fibonacci numbers up to the given Fibonacci numbers and count the number of iterations performed.
C++
// A simple C++ program to find index of given
// Fibonacci number.
#include<bits/stdc++.h>
int findIndex(int n)
{
// if Fibonacci number is less than 2,
// its index will be same as number
if (n <= 1)
return n;
int a = 0, b = 1, c = 1;
int res = 1;
// iterate until generated fibonacci number
// is less than given fibonacci number
while (c < n)
{
c = a + b;
// res keeps track of number of generated
// fibonacci number
res++;
a = b;
b = c;
}
return res;
}
// Driver program to test above function
int main()
{
int result = findIndex(21);
printf("%d\n", result);
}
// This code is contributed by Saket Kumar
Java
// A simple Java program to find index of
// given Fibonacci number.
import java.io.*;
class GFG {
static int findIndex(int n)
{
// if Fibonacci number is less
// than 2, its index will be
// same as number
if (n <= 1)
return n;
int a = 0, b = 1, c = 1;
int res = 1;
// iterate until generated fibonacci
// number is less than given
// fibonacci number
while (c < n)
{
c = a + b;
// res keeps track of number of
// generated fibonacci number
res++;
a = b;
b = c;
}
return res;
}
// Driver program to test above function
public static void main (String[] args)
{
int result = findIndex(21);
System.out.println( result);
}
}
// This code is contributed by anuj_67.
Python3
# A simple Python 3 program to find
# index of given Fibonacci number.
def findIndex(n) :
# if Fibonacci number is less than 2,
# its index will be same as number
if (n <= 1) :
return n
a = 0
b = 1
c = 1
res = 1
# iterate until generated fibonacci number
# is less than given fibonacci number
while (c < n) :
c = a + b
# res keeps track of number of
# generated fibonacci number
res = res + 1
a = b
b = c
return res
# Driver program to test above function
result = findIndex(21)
print(result)
# this code is contributed by Nikita Tiwari
C#
// A simple C# program to
// find index of given
// Fibonacci number.
using System;
class GFG
{
static int findIndex(int n)
{
// if Fibonacci number
// is less than 2, its
// index will be same
// as number
if (n <= 1)
return n;
int a = 0, b = 1, c = 1;
int res = 1;
// iterate until generated
// fibonacci number is less
// than given fibonacci number
while (c < n)
{
c = a + b;
// res keeps track of
// number of generated
// fibonacci number
res++;
a = b;
b = c;
}
return res;
}
// Driver Code
public static void Main ()
{
int result = findIndex(21);
Console.WriteLine(result);
}
}
// This code is contributed
// by anuj_67.
JavaScript
<script>
// A simple Javascript program to
// find index of given
// Fibonacci number.
function findIndex(n)
{
// If Fibonacci number
// is less than 2, its
// index will be same
// as number
if (n <= 1)
return n;
let a = 0, b = 1, c = 1;
let res = 1;
// Iterate until generated
// fibonacci number is less
// than given fibonacci number
while (c < n)
{
c = a + b;
// res keeps track of
// number of generated
// fibonacci number
res++;
a = b;
b = c;
}
return res;
}
// Driver code
let result = findIndex(21);
document.write(result);
// This code is contributed by decode2207
</script>
PHP
<?php
// A simple PHP program to
// find index of given
// Fibonacci number.
function findIndex($n)
{
// if Fibonacci number
// is less than 2,
// its index will be
// same as number
if ($n <= 1)
return $n;
$a = 0; $b = 1; $c = 1;
$res = 1;
// iterate until generated
// fibonacci number
// is less than given
// fibonacci number
while ($c < $n)
{
$c = $a + $b;
// res keeps track of
// number of generated
// fibonacci number
$res++;
$a = $b;
$b = $c;
}
return $res;
}
// Driver Code
$result = findIndex(21);
echo($result);
// This code is contributed by Ajit.
?>
Method 2 (Formula based)
But here, we needed to generate all the Fibonacci numbers up to a provided Fibonacci number. But, there is a quick solution to this problem. Let's see how! Note that computing the log of a number is an O(1) operation on most platforms.
The Fibonacci number is described as,
Fn = 1 / sqrt(5) (pow(a,n) - pow(b,n)) where
a = 1 / 2 ( 1 + sqrt(5) ) and b = 1 / 2 ( 1 - sqrt(5) )
On neglecting pow(b, n) which is very small because of the large value of n, we get
n = round { 2.078087 * log(Fn) + 1.672276 }
where round means round to the nearest integer.
Below is the implementation of the above idea.
C++
// C++ program to find index of given Fibonacci
// number
#include<bits/stdc++.h>
int findIndex(int n)
{
float fibo = 2.078087 * log(n) + 1.672276;
// returning rounded off value of index
return round(fibo);
}
// Driver program to test above function
int main()
{
int n = 55;
printf("%d\n", findIndex(n));
}
Java
// A simple Java program to find index of given
// Fibonacci number
public class Fibonacci
{
static int findIndex(int n)
{
float fibo = 2.078087F * (float) Math.log(n) + 1.672276F;
// returning rounded off value of index
return Math.round(fibo);
}
public static void main(String[] args)
{
int result = findIndex(55);
System.out.println(result);
}
}
Python3
# Python 3 program to find index of given Fibonacci
# number
import math
def findIndex(n) :
fibo = 2.078087 * math.log(n) + 1.672276
# returning rounded off value of index
return round(fibo)
# Driver program to test above function
n = 21
print(findIndex(n))
# This code is contributed by Nikita Tiwari.
C#
// A simple C# program to find
// index of given Fibonacci number
using System;
class Fibonacci {
static int findIndex(int n)
{
float fibo = 2.078087F * (float) Math.Log(n) +
1.672276F;
// returning rounded off value of index
return (int)(Math.Round(fibo));
}
// Driver code
public static void Main()
{
int result = findIndex(55);
Console.Write(result);
}
}
// This code is contributed by nitin mittal
JavaScript
<script>
// A simple Javascript program to find
// index of given Fibonacci number
function findIndex(n)
{
var fibo = 2.078087 * parseFloat(Math.log(n)) + 1.672276;
// Returning rounded off value of index
return Math.round(fibo);
}
// Driver code
var result = findIndex(55);
document.write(result);
// This code is contributed by Ankita saini
</script>
PHP
<?php
// PHP program to find index
// of given Fibonacci Number
function findIndex($n)
{
$fibo = 2.078087 * log($n) + 1.672276;
// returning rounded off
// value of index
return round($fibo);
}
// Driver code
$n = 55;
echo(findIndex($n));
// This code is contributed by Ajit.
?>
Time complexity: O(1)
Auxiliary space: O(1)
Approach:
we can solve this problem using the formula for the nth Fibonacci number, which is:
F(n) = (pow((1+sqrt(5))/2, n) - pow((1-sqrt(5))/2, n)) / sqrt(5)
We can derive the index of a given Fibonacci number using this formula. We can iterate over the values of n and calculate the corresponding Fibonacci number using the above formula until we find a Fibonacci number that is greater than or equal to the given number. At this point, we can return the index of the Fibonacci number that matches the given number.
Below is the implementation of the above approach:
C++
#include <iostream>
#include <cmath>
using namespace std;
int findIndex(int n) {
double phi = (1 + sqrt(5)) / 2;
int index = round(log(n * sqrt(5) + 0.5) / log(phi));
int fib = round((pow(phi, index) - pow(1 - phi, index)) / sqrt(5));
if (fib == n)
return index;
else
return -1; // n is not a Fibonacci number
}
int main() {
int n = 34;
int index = findIndex(n);
cout << "The index of " << n << " is " << index << endl;
return 0;
}
Java
//Java code for the above approach
import java.util.*;
public class FibonacciIndex {
public static int findIndex(int n) {
double phi = (1 + Math.sqrt(5)) / 2;
int index = (int) Math.round(Math.log(n * Math.sqrt(5) + 0.5) / Math.log(phi));
int fib = (int) Math.round((Math.pow(phi, index) - Math.pow(1 - phi, index)) / Math.sqrt(5));
if (fib == n)
return index;
else
return -1; // n is not a Fibonacci number
}
public static void main(String[] args) {
int n = 34;
int index = findIndex(n);
System.out.println("The index of " + n + " is " + index);
}
}
Python3
import math
def find_index(n):
phi = (1 + math.sqrt(5)) / 2
index = round(math.log(n * math.sqrt(5) + 0.5) / math.log(phi))
fib = round((math.pow(phi, index) - math.pow(1 - phi, index)) / math.sqrt(5))
if fib == n:
return index
else:
return -1 # n is not a Fibonacci number
def main():
n = 34
index = find_index(n)
print(f"The index of {n} is {index}")
if __name__ == "__main__":
main()
C#
using System;
class Program
{
// Function to find the index of a number in the Fibonacci sequence
static int FindIndex(int n)
{
double phi = (1 + Math.Sqrt(5)) / 2; // Golden ratio
// Calculate the index using the formula for Fibonacci numbers
int index = (int)Math.Round(Math.Log(n * Math.Sqrt(5) + 0.5) / Math.Log(phi));
// Calculate the Fibonacci number at the found index
int fib = (int)Math.Round((Math.Pow(phi, index) - Math.Pow(1 - phi, index)) / Math.Sqrt(5));
// Check if the calculated Fibonacci number is equal to n
if (fib == n)
return index;
else
return -1; // n is not a Fibonacci number
}
static void Main()
{
int n = 34;
int index = FindIndex(n);
Console.WriteLine("The index of " + n + " is " + index);
}
}
JavaScript
// Function to find the index of a number in the Fibonacci sequence
function findIndex(n) {
const phi = (1 + Math.sqrt(5)) / 2;
const index = Math.round(Math.log(n * Math.sqrt(5) + 0.5) / Math.log(phi));
const fib = Math.round((Math.pow(phi, index) - Math.pow(1 - phi, index)) / Math.sqrt(5));
if (fib === n) {
return index;
} else {
return -1; // n is not a Fibonacci number
}
}
// Main function to test the findIndex function
function main() {
const n = 34;
const index = findIndex(n);
console.log("The index of " + n + " is " + index);
}
main();
OutputThe index of 34 is 9
Time Complexity: O(1) as it involves only a few arithmetic operations.
Space Complexity: O(1) as it uses only a constant amount of memory to store the variables.
This article is contributed by Aditya Kumar.
Similar Reads
How to check if a given number is Fibonacci number?
Given a number ânâ, how to check if n is a Fibonacci number. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, .. Examples :Input : 8Output : YesInput : 34Output : YesInput : 41Output : NoApproach 1:A simple way is to generate Fibonacci numbers until the generated number
15 min read
Nth Fibonacci Number
Given a positive integer n, the task is to find the nth Fibonacci number.The Fibonacci sequence is a sequence where the next term is the sum of the previous two terms. The first two terms of the Fibonacci sequence are 0 followed by 1. The Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21Example:Input:
15+ min read
C++ Program For Fibonacci Numbers
The Fibonacci series is the sequence where each number is the sum of the previous two numbers. The first two numbers of the Fibonacci series are 0 and 1, and they are used to generate the entire series.Examples:Input: 5Output: 5Explanation: As 5 is the 5th Fibonacci number of series 0, 1, 1, 2, 3, 5
5 min read
Python Program for n-th Fibonacci number
In mathematical terms, the sequence Fn of Fibonacci numbers is defined by the recurrence relation Fn = Fn-1 + Fn-2With seed values F0 = 0 and F1 = 1.Table of ContentPython Program for n-th Fibonacci number Using Formula Python Program for n-th Fibonacci number Using RecursionPython Program for n-th
6 min read
Interesting Programming facts about Fibonacci numbers
We know Fibonacci number, Fn = Fn-1 + Fn-2. First few Fibonacci numbers are 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, .... . Here are some interesting facts about Fibonacci number : 1. Pattern in Last digits of Fibonacci numbers : Last digits of first few Fibonacci Numbers ar
15+ min read
Find nth Fibonacci number using Golden ratio
Fibonacci series = 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ........Different methods to find nth Fibonacci number are already discussed. Another simple way of finding nth Fibonacci number is using golden ratio as Fibonacci numbers maintain approximate golden ratio till infinite. Golden ratio: \varphi ={\fr
6 min read
Fast Doubling method to find the Nth Fibonacci number
Given an integer N, the task is to find the N-th Fibonacci numbers.Examples: Input: N = 3 Output: 2 Explanation: F(1) = 1, F(2) = 1 F(3) = F(1) + F(2) = 2 Input: N = 6 Output: 8 Approach: The Matrix Exponentiation Method is already discussed before. The Doubling Method can be seen as an improvement
14 min read
Tail Recursion for Fibonacci
Write a tail recursive function for calculating the n-th Fibonacci number. Examples : Input : n = 4 Output : fib(4) = 3 Input : n = 9 Output : fib(9) = 34 Prerequisites : Tail Recursion, Fibonacci numbersA recursive function is tail recursive when the recursive call is the last thing executed by the
4 min read
Sum of Fibonacci Numbers
Given a number positive number n, find value of f0 + f1 + f2 + .... + fn where fi indicates i'th Fibonacci number. Remember that f0 = 0, f1 = 1, f2 = 1, f3 = 2, f4 = 3, f5 = 5, ... Examples : Input : n = 3Output : 4Explanation : 0 + 1 + 1 + 2 = 4Input : n = 4Output : 7Explanation : 0 + 1 + 1 + 2 + 3
9 min read
Fibonacci Series
Program to Print Fibonacci Series
Ever wondered about the cool math behind the Fibonacci series? This simple pattern has a remarkable presence in nature, from the arrangement of leaves on plants to the spirals of seashells. We're diving into this Fibonacci Series sequence. It's not just math, it's in art, nature, and more! Let's dis
8 min read
Program to Print Fibonacci Series in Java
The Fibonacci series is a series of elements where the previous two elements are added to generate the next term. It starts with 0 and 1, for example, 0, 1, 1, 2, 3, and so on. We can mathematically represent it in the form of a function to generate the n'th Fibonacci number because it follows a con
5 min read
Print the Fibonacci sequence - Python
To print the Fibonacci sequence in Python, we need to generate a series of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The Fibonacci sequence follows a specific pattern that begins with 0 and 1, and every subsequent number is the sum of the two previous num
5 min read
C Program to Print Fibonacci Series
The Fibonacci series is the sequence where each number is the sum of the previous two numbers of the sequence. The first two numbers are 0 and 1 which are used to generate the whole series.ExampleInput: n = 5Output: 0 1 1 2 3Explanation: The first 5 terms of the Fibonacci series are 0, 1, 1, 2, 3.In
4 min read
JavaScript Program to print Fibonacci Series
The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1. After that, the next term is defined as the sum of the previous two terms. The recurrence relation defines the sequence Fn of Fibonacci numbers:Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1Examples:Input : 5
4 min read
Length of longest subsequence of Fibonacci Numbers in an Array
Given an array arr containing non-negative integers, the task is to print the length of the longest subsequence of Fibonacci numbers in this array.Examples: Input: arr[] = { 3, 4, 11, 2, 9, 21 } Output: 3 Here, the subsequence is {3, 2, 21} and hence the answer is 3.Input: arr[] = { 6, 4, 10, 13, 9,
5 min read
Last digit of sum of numbers in the given range in the Fibonacci series
Given two non-negative integers M, N which signifies the range [M, N] where M ? N, the task is to find the last digit of the sum of FM + FM+1... + FN where FK is the Kth Fibonacci number in the Fibonacci series. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... Examples: Input: M = 3, N = 9 Output:
5 min read
K- Fibonacci series
Given integers 'K' and 'N', the task is to find the Nth term of the K-Fibonacci series. In K - Fibonacci series, the first 'K' terms will be '1' and after that every ith term of the series will be the sum of previous 'K' elements in the same series. Examples: Input: N = 4, K = 2 Output: 3 The K-Fibo
7 min read
Fibonacci Series in Bash
Prerequisite: Fibonacci Series Write a program to print the Fibonacci sequence up to nth digit using Bash. Examples: Input : 5 Output : Fibonacci Series is : 0 1 1 2 3 Input :4 Output : Fibonacci Series is : 0 1 1 2 The Fibonacci numbers are the numbers in the following integer sequence . 0, 1, 1, 2
1 min read
R Program to Print the Fibonacci Sequence
The Fibonacci sequence is a series of numbers in which each number (known as a Fibonacci number) is the sum of the two preceding ones. The sequence starts with 0 and 1, and then each subsequent number is the sum of the two previous numbers. The Fibonacci sequence has many applications in various fie
2 min read