0% found this document useful (0 votes)
23 views1 page

Modified Fibonacci Problem... Memory Optimized...

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views1 page

Modified Fibonacci Problem... Memory Optimized...

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

/** This is a memory-optimized solution of Modified Fibonacci problem

2 * This solution takes O(n*k) time but O(k) space


3 * Recall 1 <= n <= 10^6 but 1 <= k <= 10
4 */
5

6 #include <stdio.h>
7 #include <stdlib.h>
8 #define MOD 1000000007
9

10 int main(int argc, char const *argv[])


11 {
12 int t;
13 scanf("%d", &t);
14

15 int i;
16 for (i = 0; i < t; i++)
17 {
18 long long int n, k;
19 scanf("%lld %lld", &n, &k);
20
21 int j;
22 long long int inp[k];
23 for (j = 0; j < k; j++)
24 {
25 scanf("%lld", &inp[j]);
26 // printf("%lld", inp[j]);
27 }
28

29 int prevPos, pos = 0, y;


30 long long int mul = 1;
31

32 for (j = 1; j < n-k+1; j++)


33 {
34 for (y = 0; y < k; y++)
35 {
36 mul *= inp[y];
37 if (mul >= MOD) mul %= MOD;
38 }
39
40 inp[pos] = mul;
41 mul = 1;
42 // printf("inp[%d]: %lld\n", pos, inp[pos]);
43 prevPos = pos;
44 pos = (pos+1) % k;
45 }
46
47

48 printf("%lld\n", inp[prevPos]);
49 }
50

51 return 0;
52 }

You might also like