VOOZH about

URL: https://www.geeksforgeeks.org/dsa/k-fibonacci-series/

⇱ K- Fibonacci series - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

K- Fibonacci series

Last Updated : 16 Nov, 2022

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-Fibonacci series for K=2 is 1, 1, 2, 3, ...
And, the 4th element is 3.

Input: N = 5, K = 6
Output: 1
The K-Fibonacci series for K=6 is 1, 1, 1, 1, 1, 1, 6, 11, ...

A simple approach: 
 

  • First, initialize the first 'K' elements to '1'.
  • Then, calculate the sum of previous 'K' elements by running a loop from 'i-k' to 'i-1'.
  • Set the ith value to the sum.


Time Complexity: O(N*K)
An efficient approach: 

  • First, initialize the first 'K' elements to '1'.
  • Create a variable named 'sum' which will be initialized with 'K'.
  • Set the value of (K+1)th element to sum.
  • Set the next values as Array[i] = sum - Array[i-k-1] + Array[i-1] then update sum = Array[i].
  • In the end, display the Nth term of the array.

Below is the implementation of the above approach:  


Output: 
3

 

Time Complexity: O(N)
Auxiliary Space: O(N) 
 

Comment
Article Tags:
Article Tags: