Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App

Generalized Fibonacci Numbers

Last Updated : 06 Apr, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

We all know that Fibonacci numbers (Fn) are defined by the recurrence relation  

Fibonacci Numbers (Fn) = F(n-1) + F(n-2) 
with seed values 
F0 = 0 and F1 = 1 
 

Similarly, we can generalize these numbers. Such a number sequence is known as Generalized Fibonacci number (G). 
Generalized Fibonacci number (G) is defined by the recurrence relation  

Generalized Fibonacci Numbers (Gn) = (c * G(n-1)) + (d * G(n-2)) 
with seed values 
G0 = a and G1 = b 
 

Finding Nth term

Given the four constant values of Generalized Fibonacci Numbers as a, b, c, and d and an integer N, the task is to find the Nth term of the Generalized Fibonacci Numbers, i.e. Gn.

Examples:  

Input: N = 2, a = 0, b = 1, c = 2, d = 3 
Output: 2 
Explanation: 
As a = 0 -> G(0) = 0 
b = 1 -> G(1) = 1 
So, G(2) = 2 * G(1) + 3 * G(0) = 2

Input: N = 3, a = 0, b = 1, c = 2, d = 3 
Output: 7 
 

Naive Approach: Using the given values, find each term of the series till the Nth term and then print the Nth term. 
Time Complexity: O(2N)

Another Approach: The idea is to use DP tabulation to find all the terms till the Nth terms and then print the Nth term. 
Time Complexity: O(N) 

Efficient Approach: Using matrix multiplication we can solve the given problem in log(N) time. 

\small {Given\, G(0)=a\, and\, G(1)=b, \, therefore \, G(2)=c*a+d*b } \\ \small {} \\ \begin{bmatrix} G(2) & G(1)\\ G(1) & G(0) \end{bmatrix} = \begin{bmatrix} d*b+c*a & b\\ b & a \end{bmatrix} \newline \text {Multiplying matrices on RHS will eventually give us our LHS }\\ \begin{bmatrix} G(3) & G(2)\\ G(2) & G(1) \end{bmatrix} = \begin{bmatrix} G(2) & G(1)\\ G(1) & G(0) \end{bmatrix} * \begin{bmatrix} d & 1\\ c & 0 \end{bmatrix} \newline \text {One more step } \\ \begin{bmatrix} G(4) & G(3)\\ G(3) & G(2) \end{bmatrix} = \begin{bmatrix} G(3) & G(2)\\ G(2) & G(1) \end{bmatrix} * \begin{bmatrix} d & 1\\ c & 0 \end{bmatrix} \newline \text {So by looking at the sequence above we can generalize the Nth term as... }\\ \begin{bmatrix} G(N) & G(N-1)\\ G(N-1) & G(N-2) \end{bmatrix} = \begin{bmatrix} G(2) & G(1)\\ G(1) & G(0) \end{bmatrix} * \begin{bmatrix} d & 1\\ c & 0 \end{bmatrix} ^{\!N-2}\newline \text{Now }\begin{bmatrix} d & 1\\ c & 0 \end{bmatrix} ^{\!N-2}} \text{ can be solved in log(N) time complexity }   

Below is the implementation of the above approach: 

C++
// C++ program to implement the  // Generalised Fibonacci numbers  #include <bits/stdc++.h>  using namespace std;   // Helper function that multiplies  // 2 matrices F and M of size 2*2,  // and puts the multiplication  // result back to F[][]  void multiply(int F[2][2], int M[2][2]);   // Helper function that calculates F[][]  // raised to the power N  // and puts the result in F[][]  void power(int F[2][2], int N, int m, int n);   // Function to find the Nth term  int F(int N, int a, int b, int m, int n)  {      // m 1      // n 0      int F[2][2] = { { m, 1 }, { n, 0 } };       if (N == 0)          return a;       if (N == 1)          return b;       if (N == 2)          return m * b + n * a;       int initial[2][2]          = { { m * b + n * a, b },              { b, a } };       power(F, N - 2, m, n);       // Discussed above     multiply(initial, F);       return F[0][0];  }   // Function that multiplies  // 2 matrices F and M of size 2*2,  // and puts the multiplication  // result back to F[][]  void multiply(int F[2][2], int M[2][2])  {      int x = F[0][0] * M[0][0] + F[0][1] * M[1][0];      int y = F[0][0] * M[0][1] + F[0][1] * M[1][1];      int z = F[1][0] * M[0][0] + F[1][1] * M[1][0];      int w = F[1][0] * M[0][1] + F[1][1] * M[1][1];       F[0][0] = x;      F[0][1] = y;      F[1][0] = z;      F[1][1] = w;  }   // Function that calculates F[][]  // raised to the power N  // and puts the result in F[][]  void power(int F[2][2], int N, int m, int n)  {      int i;      int M[2][2] = { { m, 1 }, { n, 0 } };       for (i = 1; i <= N; i++)          multiply(F, M);  }   // Driver code  int main()  {      int N = 2, a = 0, b = 1, m = 2, n = 3;      printf("%d\n", F(N, a, b, m, n));       N = 3;      printf("%d\n", F(N, a, b, m, n));       N = 4;      printf("%d\n", F(N, a, b, m, n));       N = 5;      printf("%d\n", F(N, a, b, m, n));       return 0;  } 
Java
// Java program to implement the  // Generalised Fibonacci numbers  import java.util.*;  class GFG{  // Function to find the Nth term  static int F(int N, int a, int b,               int m, int n)  {      // m 1      // n 0      int[][] F = { { m, 1 }, { n, 0 } };       if (N == 0)          return a;      if (N == 1)          return b;      if (N == 2)          return m * b + n * a;       int[][] initial = { { m * b + n * a, b },                          { b, a } };                               power(F, N - 2, m, n);       // Discussed below      multiply(initial, F);       return F[0][0];  }   // Function that multiplies  // 2 matrices F and M of size 2*2,  // and puts the multiplication  // result back to F[][]  static void multiply(int[][] F, int[][] M)  {      int x = F[0][0] * M[0][0] +              F[0][1] * M[1][0];      int y = F[0][0] * M[0][1] +              F[0][1] * M[1][1];      int z = F[1][0] * M[0][0] +              F[1][1] * M[1][0];      int w = F[1][0] * M[0][1] +              F[1][1] * M[1][1];       F[0][0] = x;      F[0][1] = y;      F[1][0] = z;      F[1][1] = w;  }   // Function that calculates F[][]  // raised to the power N  // and puts the result in F[][]  static void power(int[][] F, int N,                    int m, int n)  {      int i;      int[][] M = { { m, 1 }, { n, 0 } };       for(i = 1; i <= N; i++)          multiply(F, M);  }   // Driver code public static void main(String[] args) {     int N = 2, a = 0, b = 1, m = 2, n = 3;      System.out.println(F(N, a, b, m, n));          N = 3;      System.out.println(F(N, a, b, m, n));           N = 4;      System.out.println(F(N, a, b, m, n));           N = 5;      System.out.println(F(N, a, b, m, n));  } }  // This code is contributed by offbeat 
Python3
# Python3 program to implement the # Generalised Fibonacci numbers  # Function to find the Nth term def F(N, a, b, m, n):          # m 1      # n 0      F = [[ m, 1 ], [ n, 0 ]]      if(N == 0):         return a     if(N == 1):         return b     if(N == 2):         return m * b + n * a      initial = [[ m * b + n * b, b ],                            [ b, a ]]      power(F, N - 2, m, n)      multiply(initial, F)      return F[0][0]  # Function that multiplies # 2 matrices F and M of size 2*2, # and puts the multiplication # result back to F[][] def multiply(F, M):          x = (F[0][0] * M[0][0] +           F[0][1] * M[1][0])      y = (F[0][0] * M[0][1] +          F[0][1] * M[1][1])      z = (F[1][0] * M[0][0] +           F[1][1] * M[1][0])      w = (F[1][0] * M[0][1] +           F[1][1] * M[1][1])      F[0][0] = x     F[0][1] = y     F[1][0] = z     F[1][1] = w  # Function that calculates F[][] # raised to the power N # and puts the result in F[][] def power(F, N, m, n):      M = [[ m, 1 ], [ n, 0 ]]     for i in range(1, N + 1):         multiply(F, M)  # Driver code if __name__ == '__main__':      N, a, b, m, n = 2, 0, 1, 2, 3     print(F(N, a, b, m, n))      N = 3     print(F(N, a, b, m, n))      N = 4     print(F(N, a, b, m, n))      N = 5     print(F(N, a, b, m, n))  # This code is contributed by Shivam Singh 
C#
// C# program to implement the  // Generalised Fibonacci numbers  using System; class GFG{   // Function to find the Nth term  static int F(int N, int a, int b,               int m, int n)  {      // m 1      // n 0      int[,] F = { { m, 1 }, { n, 0 } };      if (N == 0)          return a;      if (N == 1)          return b;      if (N == 2)          return m * b + n * a;      int[,] initial = { { m * b + n * a, b },                          { b, a } };      power(F, N - 2, m, n);        // Discussed below      multiply(initial, F);      return F[0, 0];  }    // Function that multiplies  // 2 matrices F and M of size 2*2,  // and puts the multiplication  // result back to F[,]  static void multiply(int[,] F, int[,] M)  {      int x = F[0, 0] * M[0, 0] +              F[0, 1] * M[1, 0];      int y = F[0, 0] * M[0, 1] +              F[0, 1] * M[1, 1];      int z = F[1, 0] * M[0, 0] +              F[1, 1] * M[1, 0];      int w = F[1, 0] * M[0, 1] +              F[1, 1] * M[1, 1];        F[0, 0] = x;      F[0, 1] = y;      F[1, 0] = z;      F[1, 1] = w;  }    // Function that calculates F[,]  // raised to the power N  // and puts the result in F[,]  static void power(int[,] F, int N,                    int m, int n)  {      int i;      int[,] M = { { m, 1 }, { n, 0 } };      for(i = 1; i <= N; i++)          multiply(F, M);  }    // Driver code public static void Main(String[] args) {     int N = 2, a = 0, b = 1, m = 2, n = 3;      Console.WriteLine(F(N, a, b, m, n));     N = 3;      Console.WriteLine(F(N, a, b, m, n));      N = 4;      Console.WriteLine(F(N, a, b, m, n));      N = 5;      Console.WriteLine(F(N, a, b, m, n));  } }   // This code is contributed by shikhasingrajput  
JavaScript
<script>  // Javascript program to implement the  // Generalised Fibonacci numbers   // Function to find the Nth term  function F(N, a, b, m, n) {     var F = [ [ m, 1 ], [ n, 0 ] ]          if (N == 0)          return a;      if (N == 1)          return b;      if (N == 2)          return m * b + n * a;           var initial = [ [ m * b + n * a, b ], [ b, a ] ]          power(F, N - 2, m, n);           // Discussed below      multiply(initial, F);           return F[0][0];  }  // Function that multiplies  // 2 matrices F and M of size 2*2,  // and puts the multiplication  // result back to F[][]  function multiply(F, M)  {      var x = F[0][0] * M[0][0] +              F[0][1] * M[1][0];      var y = F[0][0] * M[0][1] +              F[0][1] * M[1][1];      var z = F[1][0] * M[0][0] +              F[1][1] * M[1][0];      var w = F[1][0] * M[0][1] +              F[1][1] * M[1][1];       F[0][0] = x;      F[0][1] = y;      F[1][0] = z;      F[1][1] = w;  }   // Function that calculates F[][]  // raised to the power N  // and puts the result in F[][]  function power(F, N, m, n)  {      var i;      var M = [ [ m, 1 ], [ n, 0 ] ];       for(i = 1; i <= N; i++)          multiply(F, M);  }   // Driver code var N = 2, a = 0, b = 1, m = 2, n = 3; document.write(F(N, a, b, m, n) + "</br>");  N = 3; document.write(F(N, a, b, m, n) + "</br>");  N = 4; document.write(F(N, a, b, m, n) + "</br>");  N = 5; document.write(F(N, a, b, m, n));      // This code is contributed by Ankita saini     </script> 

Output:
2 7 20 61

S

ssatyanand7
Improve
Article Tags :
  • Dynamic Programming
  • Mathematical
  • Matrix
  • Competitive Programming
  • DSA
Practice Tags :
  • Dynamic Programming
  • Mathematical
  • Matrix

Similar Reads

    Binary Exponentiation for Competitive Programming
    In competitive programming, we often need to do a lot of big number calculations fast. Binary exponentiation is like a super shortcut for doing powers and can make programs faster. This article will show you how to use this powerful trick to enhance your coding skills. Table of ContentWhat is Binary
    15+ min read
    Padovan Sequence
    Padovan Sequence similar to Fibonacci sequence with similar recursive structure. The recursive formula is, P(n) = P(n-2) + P(n-3) P(0) = P(1) = P(2) = 1 Fibonacci Sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55...... Spiral of squares with side lengths which follow the Fibonacci sequence. Padovan Sequ
    4 min read
    Count of different ways to express N as the sum of 1, 3 and 4
    Given a positive integer n, the task is to count the number of ways to express n as a sum of 1, 3 and 4.Examples: Input: n = 4Output: 4Explanation: There is 4 ways to represent 4 as sum of 1, 3 and 4: (1+1+1+1), (1+3), (3+1) and (4).Input: n = 3Output: 2Explanation: There is 2 ways to represent 3 as
    13 min read
    Find the Nth element of the modified Fibonacci series
    Given two integers A and B which are the first two terms of the series and another integer N. The task is to find the Nth number using Fibonacci rule i.e. fib(i) = fib(i - 1) + fib(i - 2)Example: Input: A = 2, B = 3, N = 4 Output: 8 The series will be 2, 3, 5, 8, 13, 21, ... And the 4th element is 8
    5 min read
    Program to Check Geometric Progression
    A sequence of numbers is called a Geometric progression if the ratio of any two consecutive terms is always the same.In simple terms, A geometric series is a list of numbers where each number, or term, is found by multiplying the previous term by a common ratio r. The general form of Geometric Progr
    6 min read
    Carol Number
    A Carol number is an integer of the form 4n - 2(n+1) - 1. An equivalent formula is (2n-1)2 - 2.An Interesting Property : For n > 2, the binary representation of the n-th Carol number is n-2 consecutive one's, a single zero in the middle, and n + 1 more consecutive one's. Example, n = 4 carol numb
    3 min read
    Matrix Exponentiation
    Matrix Exponentiation is a technique used to calculate a matrix raised to a power efficiently, that is in logN time. It is mostly used for solving problems related to linear recurrences.Idea behind Matrix Exponentiation:Similar to Binary Exponentiation which is used to calculate a number raised to a
    15+ min read
    String hashing using Polynomial rolling hash function
    Given a string str of length n, your task is to find its hash value using polynomial rolling hash function.Note: If two strings are equal, their hash values should also be equal. But the inverse need not be true.Examples:Input: str = "geeksforgeeks"Output: 609871790Input: str = "polynomial"Output: 9
    15+ min read
    Compute nCr%p using Fermat Little Theorem
    Given three numbers n, r and p, compute the value of nCr mod p. Here p is a prime number greater than n. Here nCr is Binomial Coefficient.Example: Input: n = 10, r = 2, p = 13 Output: 6 Explanation: 10C2 is 45 and 45 % 13 is 6. Input: n = 6, r = 2, p = 13 Output: 2Recommended PracticenCrTry It! We h
    15+ min read
    Generalized Fibonacci Numbers
    We all know that Fibonacci numbers (Fn) are defined by the recurrence relation Fibonacci Numbers (Fn) = F(n-1) + F(n-2) with seed values F0 = 0 and F1 = 1 Similarly, we can generalize these numbers. Such a number sequence is known as Generalized Fibonacci number (G). Generalized Fibonacci number (G)
    10 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences