
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find 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
#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
Advertisements