forked from Shubhanshu-1507/Sourcecode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathk-fibonacci.cpp
More file actions
54 lines (42 loc) · 933 Bytes
/
k-fibonacci.cpp
File metadata and controls
54 lines (42 loc) · 933 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <bits/stdc++.h>
using namespace std;
// Function that finds the Nth
// element of K-Fibonacci series
void solve(int N, int K)
{
vector<long long int> Array(N + 1, 0);
// If N is less than K
// then the element is '1'
if (N <= K) {
cout << "1" << endl;
return;
}
long long int i = 0, sum = K;
// first k elements are 1
for (i = 1; i <= K; ++i) {
Array[i] = 1;
}
// (K+1)th element is K
Array[i] = sum;
// find the elements of the
// K-Fibonacci series
for (int i = K + 2; i <= N; ++i) {
// subtract the element at index i-k-1
// and add the element at index i-i
// from the sum (sum contains the sum
// of previous 'K' elements )
Array[i] = sum - Array[i - K - 1] + Array[i - 1];
// set the new sum
sum = Array[i];
}
cout << Array[N] << endl;
}
// Driver code
int main()
{
long long int N = 4, K = 2;
// get the Nth value
// of K-Fibonacci series
solve(N, K);
return 0;
}