Find the GCD of N Fibonacci Numbers with given Indices in C++


Here we have to find the GCD of n Fibonacci terms with the given indices. So at first we have to get the maximum index, and generate Fibonacci terms, some Fibonacci terms are like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ….. The index is starts from 0. So the element at 0th index is 0. If we have to find gcd of Fibonacci terms at indices {2, 3, 4, 5}, then the terms are {1, 2, 3, 4}, so GCD of these numbers are 1.

We will use one interesting approach to do this task. To get the GCD of ith and jth Fibonacci term like GCD(Fibo(i), Fibo(j)), we can express it like Fibo(GCD(i, j))

Example

 Live Demo

#include <iostream>
#include <algorithm>
using namespace std;
int getFiboTerm(int n){
   int fibo[n + 2];
   fibo[0] = 0; fibo[1] = 1;
   for(int i = 2; i<= n; i++){
      fibo[i] = fibo[i - 1] + fibo[i - 2];
   }
   return fibo[n];
}
int getNFiboGCD(int arr[], int n){
   int gcd = 0;
   for(int i = 0; i < n; i++){
      gcd = __gcd(gcd, arr[i]);
   }
   return getFiboTerm(gcd);
}
int main() {
   int indices[] = {3, 6, 9};
   int n = sizeof(indices)/sizeof(indices[0]);
   cout << "GCD of fibo terms using indices: " <<
   getNFiboGCD(indices, n);
}

Output

GCD of fibo terms using indices: 2

Updated on: 21-Oct-2019

137 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements