We need to count number of configurations such that total space = N.
We have magic gems that can be either taken unsplit (occupying 1 unit) or split (occupying M units, because they become M normal gems). Normal gems cannot be split. Also we can have normal gems directly? Actually we have magic gems that can be chosen and possibly split. But what about normal gems? It seems the gems we have are magic gems initially. However, after splitting, they become normal gems. So essentially, we start with an unlimited supply of magic gems? The problem states: "Reziba has many magic gems. Each magic gem can be split into M normal gems. The amount of space each magic (and normal) gem takes is 1 unit. A normal gem cannot be split.
Reziba wants to choose a set of magic gems and split some of them, so the total space occupied by the resulting set of gems is N units. If a magic gem is chosen and split, it takes M units of space (since it is split into M gems); if a magic gem is not split, it takes 1 unit."
Interpretation: He chooses some number of magic gems from his collection. For each chosen magic gem, he decides whether to split it or not. If not split, it occupies 1 unit (as a magic gem). If split, it becomes M normal gems, occupying M units total (since each normal gem occupies 1 unit). After decisions, we have a multiset of gems (some magic, some normal) whose total occupied space (i.e., number of gems) is N. We need to count the number of distinct configurations. Two configurations are different if the number of magic gems taken differs, or the indices of gems he splits differ. Since the magic gems are presumably distinct (they are individual gems with identities), the selection of which specific magic gems are taken, and among those, which are split, matters. However, the input only gives N and M. So we assume we have an infinite supply of magic gems, each considered distinct. The process: Choose a set (finite) of magic gems. Then choose a subset of that set to split. The total space contributed is: each unsplit magic gem contributes 1, each split magic gem contributes M. So total = (number of unsplit) + M*(number of split). Let a = number of unsplit, b = number of split. Then total space N = a + M b. The total number of magic gems chosen = a + b. The distinct configurations correspond to: for each possible a,b ≥ 0 integers satisfying N = a + M b, we need to count the number of ways to choose a+b distinct magic gems from an infinite pool and then choose which b of them are split. Since magic gems are distinct and we have unlimited supply, the number of ways is infinite? That can't be. Possibly they consider that the magic gems are indistinguishable? But the note says "1 denote a magic gem, and 0 denote a normal gem." And the configurations listed are like sequences of length N? Actually the note says: "Let 1 denote a magic gem, and 0 denote a normal gem. The total configurations you can have is:
- 1 1 1 1 (None of the gems split);
- 0 0 1 1 (First magic gem splits into 2 normal gems);
- 1 0 0 1 (Second magic gem splits into 2 normal gems);
- 1 1 0 0 (Third magic gem splits into 2 normal gems);
- 0 0 0 0 (First and second magic gems split into total 4 normal gems). "
Wait. These configurations are sequences of length N (total gems) where each gem is either magic (1) or normal (0). The configurations show a specific arrangement? But the note says "total configurations you can have is: ...". They list 5 sequences. They correspond to: when N=4, M=2.
But earlier they said configurations differ by number of magic gems taken or indices of gems to split. How does that translate to a sequence of 1s and 0s? Possibly the process is: He chooses some number of magic gems and splits some. Then the resulting collection is a multiset of gems. But they are placed in some order? The problem might be: The resulting set of gems occupies N units. Since each gem occupies 1 unit, we have N gems in total. Among these N gems, some are magic (unsplit) and some are normal (from split magic gems). However, the normal gems from different split magic gems are indistinguishable? But they may be considered distinct due to originating from different magic gems? The note's sequences: For case 1 1 1 1: four magic gems, none split. So total gems = 4 magic.
Case 0 0 1 1: first magic gem splits into 2 normal gems, second magic gem unsplit, third magic gem unsplit? Wait that would be: choose 3 magic gems? Let's interpret: They wrote "0 0 1 1 (First magic gem splits into 2 normal gems)". That suggests they took two magic gems? Actually: If they take two magic gems, split the first, not split the second, then total gems: from split first: 2 normal; from second: 1 magic; total 3? That would be 3, not 4. So they must have taken three magic gems? Let's recalc: "0 0 1 1": two zeros (normal) and two ones (magic). Total = 4. To get that: Suppose they take three magic gems? Let's compute: If they take 2 magic gems, both unsplit -> 1+1=2. Not enough. If take 2 magic, split both: each yields 2 normal, total 4 normal -> 0 0 0 0. That is the last case. For 0 0 1 1, we have two normals and two magic. That would correspond to: from split one magic: 2 normal; from two magic unsplit: 2 magic; total 4. So that would be 1 split + 2 unsplit = 3 magic gems chosen. But then why "First magic gem splits"? They might be indexing the magic gems in the order they appear as magic in the final arrangement? Actually the note says: "0 0 1 1 (First magic gem splits into 2 normal gems)". That might be interpreted as: They have two magic gems placed as the last two (the ones). The first magic gem (in order) splits into two normals, which appear as the first two zeros. So effectively, they have three magic gems originally? No, they only show final arrangement of 4 gems. If only two magic gems are present as ones, then the zeros must come from splitting some magic gems, but those magic gems are no longer present as magic; they become normal. So you don't see them. So the "first magic gem" likely refers to the first magic gem among those that were taken and split, and after splitting it disappears as magic and contributes two normal gems. The final arrangement is just a sequence of the resulting gems, which includes normal gems (from splits) and unsplit magic gems. In the configuration, the unsplit magic gems appear as magic, the split ones are replaced by their M normal gems.
But the arrangement order might be arbitrary? The note seems to be enumerating distinct sequences of magic/normal gems, i.e., sequences of length N of 0s and 1s that can be obtained by some selection and splitting. However, they consider the configuration as the multiset? They list specific orders: 1 1 1 1, 0 0 1 1, 1 0 0 1, 1 1 0 0, 0 0 0 0. So these are sequences with positions. But are 0 0 1 1 and 1 0 0 1 considered different? Yes, they appear as separate entries. That suggests the order of the gems matters? Or maybe they are just representing the set of gems by listing them in some order, but the order might not be important. However they listed distinct sequences with different positions of zeros and ones. So it seems configurations are distinguished by the exact arrangement? But the problem statement says: "Two configurations are considered different if the number of magic gems Reziba takes to form them differs, or the indices of gems Reziba has to split differ." That suggests that the identity of the magic gems (which ones are taken and split) matters. In that case, if we have a+b magic gems taken, they are distinct. The resulting collection after splitting consists of: b groups of M normal gems (each group comes from a specific magic gem that was split) and a magic gems unsplit. If we consider the resulting multiset of gems, the normal gems from different split magic gems are indistinguishable, but because they come from distinct magic gems, maybe the configurations are considered different if the set of split magic gems is different, even if the final collection (ignoring origin) looks the same. But then how many configurations correspond to a given (a,b)? The number of ways to choose a+b distinct magic gems from an infinite supply is infinite. So that can't be. Therefore, the magic gems must be considered indistinguishable, or rather we are not counting which specific magic gems are chosen; we are just counting the number of ways to decide on splitting such that total space = N, with the assumption that magic gems are unlimited but identical. The "indices of gems" might refer to positions in the sequence? Or maybe the process is: Reziba takes some magic gems and decides which ones to split. He then places all resulting gems in a line. The resulting sequence of N gems (each either magic or normal) is what we call configuration. Two configurations are different if the sequences differ. But the splitting decisions and the identities of the original magic gems might produce different sequences because the normal gems from a split magic gem might be considered as a block? However, the note indicates that for the case where two magic gems are split (both split), we get four normal gems: 0 0 0 0. That's a single configuration, not multiple (e.g., if the two split gems are distinct, you might think that the order of their resulting normal gems could be interleaved? But the note says only one configuration: 0 0 0 0. So they are not distinguishing based on which split gem produced which normal gems, because all normal gems are identical. So the configuration is just the multiset? But if we had split one magic gem and left two magic gems unsplit, the note lists three distinct sequences: 0 0 1 1, 1 0 0 1, 1 1 0 0. That's three arrangements. They didn't list 0 1 0 1, 0 1 1 0, 1 0 1 0? Actually those would also be possible if we consider all permutations of two zeros and two ones? The number of binary strings of length 4 with exactly two zeros and two ones is C(4,2)=6. But they only list 3. So they are not just all permutations. So there must be some additional constraint: maybe the normal gems from a particular split magic gem are considered as an indistinguishable block that must appear together? In the note, the zeros appear consecutively in all listed configurations: 0 0 as a block, and the ones appear as a block? Let's check:
- 0 0 1 1: zeros block then ones block.
- 1 0 0 1: one 1, then zeros block, then one 1.
- 1 1 0 0: ones block then zeros block.
They didn't list 0 1 0 1, which would interleave zeros and ones. So indeed, zeros are contiguous. This suggests that the M normal gems resulting from a single split magic gem are indistinguishable and must occupy a contiguous block in the final arrangement? But the problem statement does not mention ordering. Possibly the configuration is not about ordering but about the pattern of which magic gems (by their order) are split. The note might be illustrating the configurations with a representation where magic gems are represented as 1 and normal as 0, and the positions correspond to the order of the chosen magic gems? Let's think: "Let 1 denote a magic gem, and 0 denote a normal gem." They list sequences of 1 and 0. In the explanation, they say: "The total configurations you can have is:
- 1 1 1 1 (None of the gems split);
- 0 0 1 1 (First magic gem splits into 2 normal gems);
- 1 0 0 1 (Second magic gem splits into 2 normal gems);
- 1 1 0 0 (Third magic gem splits into 2 normal gems);
- 0 0 0 0 (First and second magic gems split into total 4 normal gems)."
They refer to "first magic gem", "second magic gem", "third magic gem". This suggests that they have a fixed ordered list of magic gems that are taken? Maybe Reziba takes some number, say k, of magic gems. They are indexed in the order they are taken (or perhaps they have an order). Then he decides which of these k to split. After splitting, we have a sequence consisting of: for each of the k gems, if it is not split, we put a magic gem (1); if it is split, we put M normal gems (0...0). So the resulting sequence is of length N, and it is obtained by replacing each split magic gem with a block of M zeros, and each unsplit magic gem with a single 1. So the sequence is a concatenation of blocks: for each of the k gems in order, either a block of M zeros (if split) or a block of one 1 (if not split). So the sequence is determined by: a number k (the number of magic gems chosen), and a subset of these k that are split, such that total length = number of unsplit (1 each) + M * number of split = N. The order of blocks is fixed by the indices of the magic gems.
Thus, the configurations correspond to binary strings of length N consisting of runs of ones and zeros? Actually each block is either a single 1 or M zeros. So the total length N is sum of a number of blocks. The blocks come in a sequence, and each block is either 1 or M. The blocks are in order, and the choice of which positions (indices) are split determines the pattern. Moreover, the magic gems are considered distinguishable only by their order in the sequence; but they are identical otherwise. So the number of configurations is the number of sequences of blocks (i.e., ways to write N as a sum of 1's and M's, where order matters). But careful: If we have a sequence of blocks, that is essentially a composition of N using parts of size 1 or M. However, note that the blocks are labeled by the index of the magic gem. If we have a composition of N into parts each either 1 or M, then that directly gives a configuration: each part corresponds to one magic gem; if the part is 1, that gem is unsplit; if the part is M, that gem is split. The total number of magic gems chosen is the number of parts. The set of indices that are split is precisely the positions where the part equals M. So each composition yields a distinct configuration (since the order of parts matters). And indeed, for N=4, M=2, the compositions using 1 and 2 are:
- 1+1+1+1 -> four parts of 1 => all unsplit: config: 1 1 1 1.
- 1+1+2 -> three parts: order matters? Composition 1+1+2 yields blocks: 1,1,2 -> sequence: 1 1 0 0 (since block of 2 zeros). That's 1 1 0 0.
- 1+2+1 -> 1,2,1 -> sequence: 1 0 0 1.
- 2+1+1 -> 2,1,1 -> sequence: 0 0 1 1.
- 2+2 -> two parts: 2,2 -> sequence: 0 0 0 0.
That's exactly the five configurations listed. So the number of configurations = number of ways to write N as an ordered sum of 1's and M's (i.e., compositions of N using parts 1 and M). That matches the examples: N=3, M=2 gives compositions: 1+1+1, 1+2, 2+1 -> 3 configurations. Output 3. Yes.
So the problem reduces to: Count the number of compositions of integer N (positive integer) where each part is either 1 or M (M≥2). This number is like Fibonacci-like but with step M. That is, let f(N) be the number of such compositions. Then f(0) maybe 1? For positive N, recurrence: f(N) = f(N-1) + f(N-M) if N>=M, else f(N) = f(N-1) only (since N-M negative). Base: f(0) = 1 (empty composition?). But careful: For N>0, we need compositions using parts 1 and M. Standard recurrence: f(N) = f(N-1) + f(N-M) (if N>=M), with f(0)=1, and f(k)=0 for k<0. For N=1: f(1)=f(0)=1 (only composition 1). For N=2, M=2: f(2)=f(1)+f(0)=1+1=2? But compositions of 2 using parts 1,2: 1+1 and 2 -> 2 compositions. Yes. For N=4, M=2: f(4)=f(3)+f(2)=? f(3)=f(2)+f(1)=2+1=3, f(2)=2, total 5. Good.
So the answer is f(N) mod 1e9+7, where N up to 1e18, M up to 100.
We need to compute this linear recurrence of order M: f(N) = f(N-1) + f(N-M). But note that the recurrence is not homogeneous of order M? Actually f(N) depends on N-1 and N-M. That's a linear recurrence with characteristic equation: x^M = x^{M-1} + 1? Wait, we can rewrite: f(N) - f(N-1) - f(N-M)=0. That is a linear recurrence of order M (since highest index difference M). But we can also define it as: f(N) = f(N-1) + f(N-M) for N>=M; and for 0<=N<M, we have base values: f(0)=1, and for 1 <= N < M, f(N)=f(N-1) (since only part 1 possible) => f(N)=1 for N=1..M-1? Let's check: For N=1, only composition 1, so 1. For N=2, if M>2, then only 1+1 -> 1 composition. So indeed f(N)=1 for 0<N<M. But for N=M, compositions: all ones (M parts of 1) plus one part of M, so 2 compositions. So f(M)=2.
So we have a linear recurrence of order M, but we can compute f(N) efficiently using matrix exponentiation (since M ≤ 100, N up to 1e18). Define state vector of length M: maybe we want to compute f(N) based on previous M values. Since recurrence uses f(N-1) and f(N-M), we can set state as [f(N), f(N-1), ..., f(N-M+1)]^T. Then next state for N+1: f(N+1) = f(N) + f(N+1-M) = f(N) + (the last component of state, which is f(N-M+1)?) Actually careful: For N+1, f(N+1) = f(N) + f(N+1-M). In the state vector, we have f(N), f(N-1), ..., f(N-M+1). The value f(N+1-M) is the last component? Since we have f(N-M+1) in the vector, that is f(N-M+1) = f((N+1)-M). Yes, because (N+1)-M = N-M+1. So indeed f(N+1) = f(N) + state_last. So we can update.
Alternatively, we can define state as [f(N), f(N-1), ..., f(N-M+1)] of length M. Then transition to [f(N+1), f(N), ..., f(N-M+2)] where f(N+1) = f(N) + f(N-M+1). So the transition matrix T is M x M: first row: [1, 0, 0, ..., 0, 1]? Actually f(N+1) = 1f(N) + 0f(N-1) + ... + 0f(N-M+2) + 1f(N-M+1). So first row: coefficients: for f(N) coefficient 1, for f(N-M+1) coefficient 1, others 0. Then the rest of rows shift: row 2: [1,0,0,...,0]? Wait, we need to shift: the second component of new state is f(N) which is the first component of old state. So row 2: [1,0,0,...,0]. Row 3: [0,1,0,...,0] to shift f(N-1) to third component? Actually let's define state as S_N = [f(N), f(N-1), ..., f(N-M+1)]^T. Then S_{N+1} = [f(N+1), f(N), f(N-1), ..., f(N-M+2)]^T. So:
- f(N+1) = 1f(N) + 0f(N-1) + ... + 0f(N-M+2) + 1f(N-M+1).
- f(N) (second component) = 1f(N) + 0f(N-1) + ... + 0*f(N-M+1) (i.e., picks the first component).
- f(N-1) (third component) = picks the second component.
- ...
- f(N-M+2) (last component) = picks the (M-1)-th component? Actually old state indices: component 1: f(N), component 2: f(N-1), ..., component M-1: f(N-M+2), component M: f(N-M+1). New state: component 1: f(N+1); component 2: f(N); component 3: f(N-1); ...; component M: f(N-M+2). So for i from 2 to M, new component i = old component i-1. So row i for i>=2: has a 1 at column i-1, zeros elsewhere.
Thus T is an MxM matrix:
- Row 1: column 1 = 1, column M = 1, others 0.
- Row i (2 <= i <= M): column i-1 = 1, others 0.
That is a companion matrix for the recurrence.
Then we need to compute f(N). We know base values for N from 0 to M-1. But our state definition includes f(N) for N >= M? We can start from initial state S_{M-1}? Actually we need a state that allows us to compute for N >= M. Let's define base N = M-1: we know f(0), f(1), ..., f(M-1). To get state S_{M-1} = [f(M-1), f(M-2), ..., f(0)] (since N = M-1, then N-M+1 = 0). So we have vector of length M. Then we can multiply by T to get S_{M}, S_{M+1}, ... up to S_N.
But N can be as low as 1. So handle small N directly? We can compute using fast exponentiation if N>=M, else we can output 1 if N<M? Wait f(N)=1 for 0<N<M? Actually for N>0 and N<M, the only composition is all ones, so f(N)=1. For N=0? Not needed because N>=1. So for 1 ≤ N < M, answer = 1. For N=M, answer = 2. For N>M, we need recurrence.
Thus algorithm: if N < M: return 1. Else compute f(N) using matrix exponentiation of T^(N-(M-1)) applied to initial state S_{M-1} and take first component mod MOD.
But careful: for N = M, we have S_{M-1} = [f(M-1), f(M-2), ..., f(0)] = [1,1,...,1] (M values: f(0)=1, f(1)=1,..., f(M-1)=1). Then S_M = T * S_{M-1} = [f(M-1)+f(0) = 1+1=2, f(M-1)=1, f(M-2)=1, ..., f(1)=1] => first component = 2, which matches f(M). Good.
So to compute f(N) for N >= M-1, we need to compute T^{N-(M-1)} * S_{M-1}. Since M up to 100, matrix multiplication O(M^3 log N) is feasible (100^3=1e6, times log2(1e18) ~ 60, total ~ 60e6 = 60 million operations, which is okay in C++ but Python might be borderline but possibly okay if optimized using modular arithmetic and maybe using list comprehensions. But we can do better: Since the matrix is sparse, we can implement multiplication as O(M^2) per multiply? Actually T is mostly zeros; but typical matrix exponentiation uses O(M^3) if using naive multiplication. However, M=100, M^3=1e6, times 60 = 60 million, which is fine in Python with moderate optimization? 60 million modular multiplications and additions might be okay within time limit (likely 1-2 seconds? Python can do about 50-100 million simple ops per second? Possibly borderline but okay with PyPy. However we can also use linear recurrences and fast doubling using polynomial exponentiation (linear recurrence with constant coefficients) via Kitamasa method, which is O(M^2 log N) or O(M log M log N) using FFT but M small so O(M^2 log N) is similar to matrix O(M^3 log N) but M^2=10k vs M^3=1e6, so better. However matrix exponentiation is simpler to implement correctly.
But note: MOD = 1e9+7, which fits in Python ints.
Given that N up to 1e18, log2 ~ 60. So matrix exponentiation with M=100: 60 * (100^3) = 60 * 1,000,000 = 60,000,000 multiplications/adds. In Python, 60 million operations might be okay if each operation is simple integer arithmetic and we avoid overhead. But we need to multiply two MxM matrices each step? Actually exponentiation by squaring: we need to multiply matrices (T^a * T^b). That's M^3 per multiplication. However, we can optimize because T is constant and we need T^p. We'll compute powers of T via squaring, then multiply the state vector (Mx1) by the appropriate power. That reduces the number of matrix-vector multiplications: we can exponentiate by binary exponentiation: compute T powers, and then multiply the vector by each relevant power. But we still need to multiply matrices to compute powers. For each bit, we square the matrix: that's matrix-matrix multiplication (M^3). For about 60 bits, that's 60 matrix squarings. Then we multiply the vector by each relevant power (matrix-vector multiplication O(M^2) per bit). So total ~60 * M^3 + 60 * M^2. That's about 60 * 1e6 + 60 * 1e4 = 60 million + 0.6 million = 60.6 million. That's okay.
Alternatively, we can use exponentiation on the linear recurrence directly using linear rec techniques that are O(M^2 log N) maybe 60 * 10k = 600k, which is even better. But simplicity: matrix exponentiation is fine.
We need to be careful with indexing and base cases. Also consider that N can be huge; we must use modulo.
Let's formalize:
Define f(n) for integer n >= 0:
- f(0) = 1 (empty composition? But we may not need it for N>=1, but for recurrence it's needed)
- For n>0: f(n) = f(n-1) + (f(n-M) if n>=M else 0). Actually the recurrence holds for n>=M, and for n<M, f(n) = 1 (since only composition is n ones). But that can be derived from f(0)=1 and recurrence with f(n) = f(n-1) for n<M? Actually if we define f(n) = f(n-1) for 0<n<M with f(0)=1, then f(1)=1, f(2)=1,... f(M-1)=1. Then for n=M, f(M)=f(M-1)+f(0)=2. So it's consistent.
So we can compute f(N) using matrix exponentiation.
Now, since M can be up to 100, we need to build matrix of size M.
But wait: what about the case M > N? Then answer = 1. So handle that.
Edge: N=0? Not allowed (N>=1).
Now, confirm with examples: N=4 M=2 -> M=2, N>=M. So we compute.
Set M=2. State size 2. S_{M-1}=S_{1}=[f(1), f(0)] = [1,1]. T = [[1,1],[1,0]]? Let's compute: M=2, rows: row1: col1=1, colM=1 => col1=1, col2=1; row2: shift: col1=1? Actually row2: column i-1= column1 => row2 col1=1, others 0. So T = [[1,1],[1,0]]. That's Fibonacci matrix. So S_N = T^{N-1} * S_1? Let's see: For N=4, we want f(4). Compute T^3 * S_1? Actually N=4, M-1=1 => exponent = N-(M-1)=3. T^3 = [[3,2],[2,1]]? Multiply by S_1=[1,1] gives [3+2=5,2+1=3] so f(4)=5. Good.
For N=3, exponent=2: T^2=[[2,1],[1,1]] times [1,1] gives [3,2] => f(3)=3.
Works.
Now, we should also consider possibility that M could be 1? But constraints say M>=2, so fine.
Thus solution: compute f(N) as number of compositions with parts 1 and M.
Now, note: there might be alternative combinatorial interpretation: f(N) = sum_{k=0}^{⌊N/M⌋} binomial(N - (M-1)k, k). Because if we have b splits (b parts of M) and a unsplit (a parts of 1), with a + M b = N => a = N - M b. Total number of parts = a + b = N - (M-1)b. The number of compositions with exactly b parts of size M and a parts of size 1 is the number of ways to choose positions for the b blocks of size M among the total (a+b) blocks, which is C(a+b, b) = C(N - (M-1)b, b). Because each composition is a sequence of a+b blocks, b of which are M and a are 1. So total f(N) = sum_{b=0}^{⌊N/M⌋} C(N - (M-1)b, b). That sum also works. For N=4,M=2: b=0: C(4,0)=1; b=1: N-(M-1)b=4-1=3, C(3,1)=3; b=2: 4-2=2, C(2,2)=1; total=5. For N=3,M=2: b=0: C(3,0)=1; b=1: 3-1=2, C(2,1)=2; total=3. So formula valid.
We could compute f(N) using that sum directly, but N up to 1e18, b up to N/M which could be up to 5e17, not feasible.
So recurrence/matrix exponentiation is the way.
Now, we need to implement matrix exponentiation modulo MOD.
But careful: M up to 100, but state size M. So matrix exponentiation O(M^3 log N) = 100^3=1e6, times log2(N) ~ 60 => 60e6 operations. In Python, 60 million integer multiplications and additions mod 1e9+7 might be okay with PyPy if optimized (using list of lists, maybe not). We can try to improve by using numpy? Not allowed usually. But we can also use the linear recurrence method with polynomial exponentiation (Kitamasa) which is O(M^2 log N) ~ 10000*60 = 600k, much faster.
I'll consider implementing Kitamasa or matrix exponentiation but with careful coding. Since M is only up to 100, I think matrix exponentiation will pass in Python with PyPy, but to be safe, I can implement exponentiation of companion matrix using exponentiation by squaring on the matrix but use some optimization: Because the matrix is sparse, we can implement multiplication of companion matrices more efficiently than generic O(M^3). However, squaring a companion matrix might produce a dense matrix, so after a few squarings it becomes dense. So we can't maintain sparsity easily.
Alternatively, we can use linear recurrence exponentiation via doubling using polynomial multiplication and polynomial modulo, but that might be more complex. However, there is a known method for linear recurrences: we can compute f(N) using matrix exponentiation with exponentiation by squaring on the transition matrix, but we can also use exponentiation on the linear recurrence using linear rec in O(M^2 log N) via "linear recurrence using exponentiation of companion matrix in the polynomial domain" (like using the Cayley-Hamilton theorem). Since M <= 100, implementing Kitamasa might be simpler: we need to compute the characteristic polynomial and then use exponentiation of x^N mod that polynomial to get coefficients, then dot with initial values. But we can also use binary exponentiation with matrix, which is straightforward.
Given constraints, 60 million operations: each operation involves multiplication and addition mod 1e9+7. In Python, 60 million operations might be about 0.6-1.2 seconds? Actually Python can do about 50 million integer ops per second on PyPy? Possibly slower. But with loops in Python, 60 million may be 2-3 seconds, which might be acceptable if time limit is generous. However, we need to multiply matrices, which involves triple nested loops. Each inner operation: c[i][j] = (c[i][j] + a[i][k] * b[k][j]) % MOD. That's many operations. For M=100, each multiplication does about M^3 = 1e6 scalar operations (multiplications and additions). 60 such multiplications => 60e6 operations. That might be okay. But we must also consider that Python loops are slow; 60e6 might be about 2-3 seconds in PyPy if optimized? But we also have overhead for function calls, etc. I think it's borderline but likely acceptable given typical contest time limits (2 seconds? Maybe 1 second? Hard to know). I've seen problems where M up to 100, N up to 1e18, solved with matrix exponentiation in Python passes if optimized.
We can also reduce constant by using list comprehensions and pre-allocation, or using numpy, but that's often not allowed. Another approach: use exponentiation with exponent decomposition and multiply only vector by matrix, not full matrix multiplication? We can compute T^p * v by exponentiation by squaring where we square T and multiply v only when needed, but we still need to square T (matrix multiplication). Could we avoid full matrix squaring by using linear rec doubling that computes recurrences directly? There is a technique known as "linear recurrence with constant coefficients using exponentiation by squaring on polynomials" which is O(M^2 log N). That would be much faster.
Let me outline Kitamasa method:
Given recurrence: f(n) = c1 f(n-1) + c2 f(n-2) + ... + cM f(n-M) for n >= M, with coefficients c_i. In our case, f(n) = f(n-1) + f(n-M), i.e., c1=1, cM=1, others 0.
We want f(N) given initial values f(0), f(1), ..., f(M-1).
Kitamasa: we compute the coefficients of the linear combination of initial terms that give f(N). That is, we find a polynomial P(x) = x^N mod characteristic polynomial Q(x) = x^M - c1 x^{M-1} - ... - cM. Then f(N) = sum_{i=0}^{M-1} p_i f(i). The polynomial remainder can be computed using binary exponentiation with polynomial multiplication and polynomial modulo. Since M <= 100, polynomial multiplication naive O(M^2) is fine. So total O(M^2 log N). That is ~ 100^2 * 60 = 600,000 operations, which is very fast.
Thus I'd prefer to implement Kitamasa. But we must be careful with indices: our recurrence f(n) = f(n-1) + f(n-M) for n>=M. So the characteristic polynomial: x^M = x^{M-1} + 1? Actually the recurrence is f(n) - f(n-1) - f(n-M) = 0 => x^M - x^{M-1} - 1 = 0? Let's derive: Assume f(n) = x^n, then plug: x^n - x^{n-1} - x^{n-M} = 0 => divide by x^{n-M}: x^M - x^{M-1} - 1 = 0. So the characteristic polynomial is Q(x) = x^M - x^{M-1} - 1. But careful: the recurrence is f(n) = f(n-1) + f(n-M). So standard form: f(n) = 1 * f(n-1) + 0 * f(n-2) + ... + 1 * f(n-M). So coefficients: c1=1, c2=0, ..., c_{M-1}=0, cM=1. So the polynomial is x^M - c1 x^{M-1} - c2 x^{M-2} - ... - cM = x^M - x^{M-1} - 1.
But wait: In Kitamasa we typically use polynomial: x^M = c1 x^{M-1} + c2 x^{M-2} + ... + cM. So Q(x) = x^M - (c1 x^{M-1} + ... + cM). So that's consistent.
Now, we need initial values f(0), f(1), ..., f(M-1). We have f(0)=1, and for 1 <= i < M, f(i) = 1. So we have them.
But careful: f(0) is defined as 1? In composition context, f(0) is 1 (empty composition). For N>=1, we don't need f(0). But it's used in recurrence and Kitamasa for n < M. That is fine.
Thus we can compute f(N) using Kitamasa.
Let's verify for M=2: Q(x)=x^2 - x - 1. Compute f(N) = coefficient of x^? Actually Kitamasa: We compute polynomial P(x) = x^N mod Q(x), which yields a polynomial of degree < M (i.e., degree < 2) => a0 + a1 x. Then f(N) = a0 * f(0) + a1 * f(1). For Fibonacci, f(0)=0? Wait Fibonacci standard: F0=0, F1=1. But here f(0)=1, f(1)=1. So our recurrence is f(2)=f(1)+f(0)=2, f(3)=f(2)+f(1)=3,... So that's like shifted Fibonacci: f(n) = Fib(n+1)? Actually Fib: F1=1, F2=1, F3=2, F4=3, F5=5. Here f(1)=1, f(2)=2, f(3)=3, f(4)=5. So f(n) = Fib(n+1)? Check: n=1 => Fib(2)=1 => f(1)=1 OK; n=2 => Fib(3)=2 => f(2)=2 OK; n=3 => Fib(4)=3 OK; n=4 => Fib(5)=5 OK. So indeed f(n)=Fib(n+1). Now using Kitamasa: For N=4, compute x^4 mod (x^2 - x -1). Divide: x^4 = (x^2 - x -1)(x^2 + x + 2) + (3x+2)? Actually compute: We want remainder of degree <2. We can compute: x^4 mod Q =? Since Q = x^2 - x -1, we can reduce: x^2 = x + 1, x^3 = xx^2 = x*(x+1) = x^2 + x = (x+1)+x = 2x+1, x^4 = xx^3 = x(2x+1)=2x^2+x = 2(x+1)+x = 2x+2+x = 3x+2. So remainder = 2 + 3x. Then f(4) = a0f(0) + a1f(1) = 21 + 31 =5. Works.
So Kitamasa yields correct answer.
Therefore, implement Kitamasa:
Input: N (int up to 1e18), M (2..100). Output f(N) mod MOD.
We need to compute polynomial R(x) = x^N modulo Q(x) = x^M - x^{M-1} - 1. Since coefficients can be large, we work modulo MOD.
Algorithm: binary exponentiation on polynomial exponent N. We'll maintain a polynomial poly representing current power (x^k). Initially poly = [1] (degree 0, representing x^0 = 1). Also we have base = [0,1]? Actually we need to compute x^N mod Q. We can do exponentiation by squaring: Start with result polynomial = 1 (degree 0). Let base = x (represented as polynomial [0,1] of degree 1). Then for each bit of N from LSB to MSB: if bit set, result = (result * base) mod Q; then base = (base * base) mod Q. All polynomial operations modulo MOD and modulo Q.
Polynomial multiplication: given two polynomials A and B of degrees < M (since we keep them reduced mod Q), their product can be of degree up to 2M-2. Then we reduce mod Q. So we need a function to multiply two polynomials and then modulo by Q. Since M ≤ 100, naive O(M^2) multiplication and O(M^2) reduction is fine.
But note: In exponentiation, we keep base and result polynomials of degree < M after reduction. So multiplication of two polynomials of degree < M yields degree < 2M-2. Then we reduce modulo Q. Reduction: Given polynomial C of degree up to 2M-2, we need C mod Q. Since Q is monic of degree M (coeff of x^M is 1), we can iteratively reduce highest degree term: For i from deg(C) down to M, if C[i] != 0, then we subtract C[i] * (x^{i-M} * Q(x)). But Q(x) = x^M - x^{M-1} - 1. So x^{i} mod Q = x^{i-M} * (x^{M-1} + 1) = x^{i-1} + x^{i-M}? Actually compute: Since Q = x^M - x^{M-1} - 1, we have x^M ≡ x^{M-1} + 1 (mod Q). Then x^{i} = x^{i-M} * x^M ≡ x^{i-M}*(x^{M-1}+1) = x^{i-1} + x^{i-M} (mod Q). This recurrence can be used repeatedly. But for reduction, we can do: while deg >= M: let d = deg(C). Then we can subtract C[d] * (x^{d-M} * Q) from C. That subtraction: C[d] times (x^{d-M} * (x^M - x^{M-1} - 1)) = C[d] * (x^{d} - x^{d-1} - x^{d-M}). So we update: C[d] becomes 0; C[d-1] += C[d]; C[d-M] += C[d]; all modulo MOD. But careful: if d-M could be negative? Since d >= M, d-M >= 0. So okay. That reduces one term. However, after this, the degree may reduce but still could be >= M if next highest term is >= M. So we need to loop. Since M is small, we can just iterate from highest degree down to M and perform this reduction in one pass: for i from deg(C) down to M, if C[i] != 0, then add C[i] to C[i-1], add C[i] to C[i-M], and set C[i] = 0. But note: when we process from high to low, after adjusting C[i-1] and C[i-M], these may become nonzero and could increase degree? But i-1 < i, and i-M < i, so processing from high ensures that when we get to lower indices, we might have introduced new high-degree terms? Actually, after we zero C[i] and add to C[i-1] and C[i-M], C[i-1] might become a coefficient for degree i-1, which could be >= M. Since we are iterating downwards, we will later process i-1 if i-1 >= M. So that's fine. But there is a nuance: when we add to C[i-M], that index could be >= M as well? i-M could be >= M if i >= 2M. But our polynomial C originally had degree up to 2M-2, so i max = 2M-2, then i-M max = M-2, which is < M. So after the first reduction, the maximum index that gets incremented is i-1, which is at most 2M-3. That could still be >= M. So we need to continue until all coefficients for degrees >= M are zero. The loop from high to low as described will handle it as long as we keep going until no degree >= M. But careful: when we modify C[i-1], if i-1 >= M, we will eventually process it when we get to that index in the descending loop (since we are going downwards). However, if after processing a high index we add to a lower index that is still > i? No, i-1 < i, so it will be processed later in the same descending loop because we are moving downwards. So one pass from high to low (starting from current max degree) will reduce all to < M, as long as we update max degree dynamically? Actually we need to keep track of current highest degree after modifications. Since modifications only affect indices lower than i, the current pointer i is decreasing. If we start at max_deg, and as we go down, we may add to some index j that is less than current i but maybe greater than some indices we already processed? For example, suppose M=3, and we have C[4] nonzero. Process i=4: add C[4] to C[3] and C[1]; set C[4]=0. Now C[3] might become nonzero. But we are at i=4, next i=3. So we will process i=3 later. That's fine. Now suppose we have C[5] nonzero. Process i=5: add to C[4] and C[2]; set C[5]=0. Now C[4] gets a contribution, but we are past i=5 and moving down, i=4 is next, so we will process it. So descending loop works.
Thus reduction function: given list C of length maybe 2M (or we can maintain as list of length up to maybe 2M-1), we repeatedly for i from len(C)-1 down to M: if i < len(C) and C[i]!=0: C[i-1] = (C[i-1] + C[i]) % MOD; if i-M >=0: C[i-M] = (C[i-M] + C[i]) % MOD; C[i] = 0. After processing all i from high down to M, we can truncate to length M (keeping indices 0..M-1). But careful: the addition to C[i-1] might cause C[i-1] to become non-zero, but i-1 >= M? That will be processed when i reaches i-1 (since we loop descending). However, if we are using a fixed for loop with range(max_deg, M-1, -1), and max_deg is initially the highest index where C has non-zero. But when we add to C[i-1], if i-1 > max_deg? It can't be because i-1 < i ≤ max_deg. So it's within the range we will process if we loop down to M. But what if i-M > max_deg? i-M is less than i, and since i ≤ max_deg, i-M ≤ max_deg - M < max_deg, so also less than max_deg. So it's within the lower part, not a problem for the loop as we are going downwards; we might have already passed over index i-M if i-M > current i? Wait: our loop index i goes from high to low. Suppose we are at i, and we add to C[i-M]. Since i-M < i, and we are moving downwards, we will have already processed index i-M? Actually i-M is lower than i, so when we are at i, we have not yet processed indices lower than i; we are moving downwards, so after processing i, we will go to i-1, i-2, ... eventually reaching i-M. So we will process i-M later. So that's fine. But we need to ensure that C[i-M] is within the array and that we consider its contribution for further reduction if i-M ≥ M. So descending loop works. However, we need to ensure that the array length covers up to max degree that could appear. Initially C length may be up to 2M-1. While reducing, we might add to index i-M, which is < M maybe, but if i-M ≥ M? As argued earlier, i ≤ 2M-2, so i-M ≤ M-2 < M. So after first reduction, all indices that get added are < M except possibly i-1 which could be ≥ M. So the maximum index we need to handle is up to 2M-2? But after we zero C[i], we might later add to some index that is still >= M (i-1). That index will be processed later. But the highest index that could appear after addition is i-1, which at most 2M-3. So it's still within initial max. So if we allocate C with length 2*M (or simply use a list that we extend as needed), descending loop from current max index down to M works if we dynamically update the max index as we go? Actually we can just loop from len(C)-1 down to M. After we modify, we might set some coefficients beyond current length? No, indices are within length. However, if we zero C[i] and add to C[i-1], the length remains same. So it's safe.
But we could also implement reduction using the relation x^M = x^{M-1} + 1, so we can precompute a function that reduces any degree polynomial to degree < M by repeatedly replacing x^{k} with x^{k-1} + x^{k-M} for k>=M. That's essentially same.
Simpler: implement polynomial multiplication and then use a function reduce(poly) that while len(poly) > M: let d = len(poly)-1; if d >= M: we take coeff = poly[d]; if coeff != 0: then poly[d-1] = (poly[d-1] + coeff) % MOD; if d-M >= 0: poly[d-M] = (poly[d-M] + coeff) % MOD; pop last (or set to 0). Then continue. But we should be careful to process from high to low: We could while max degree >= M: for i in range(max_deg, M-1, -1): process. But if we process in descending order and keep max_deg updated, we can do one pass.
But maybe even simpler: after multiplication, we can compute C_mod = [0]*M, and then for i from 0 to len(C)-1: add C[i] * x^i to the result, using reduction rule: for each term, we can add it to the appropriate lower degrees by applying the recurrence iteratively. But that would be O(M^2) as well.
Given M small, we can just perform polynomial modulo by using the standard polynomial long division algorithm: given C of degree D, compute remainder R of degree < M by iteratively subtracting multiple of Q. Since Q is monic, we can do:
for i in range(D, M-1, -1):
if C[i] != 0:
# subtract C[i] * x^{i-M} * Q(x)
C[i-M] = (C[i-M] + C[i]) % MOD # because Q has -x^{M-1} -1, so subtracting C[i]*x^{i-M}*Q: we add C[i] to coefficient of x^{i-M}*x^{M-1} = x^{i-1}? Actually careful: Q = x^M - x^{M-1} - 1. So x^{i-M} * Q = x^i - x^{i-1} - x^{i-M}. So to compute C mod Q, we want to replace x^i by x^{i-1} + x^{i-M}. So we can do: C[i-1] = (C[i-1] + C[i]) % MOD; C[i-M] = (C[i-M] + C[i]) % MOD; C[i] = 0. That's exactly the transformation. So we can do for i from D down to M: if C[i]!=0: then C[i-1] = (C[i-1] + C[i]) % MOD; C[i-M] = (C[i-M] + C[i]) % MOD; C[i] = 0. After processing all i, the coefficients for indices >= M become zero. Then the remainder is the first M coefficients. But we must ensure that when we add to C[i-1], if i-1 >= M, we might later process it, and we are processing i descending, so it's fine. But after we set C[i]=0, we don't need to pop; we can just ignore indices beyond M-1 later. However, note that we may have added to C[i-M] which is < M, so no further processing needed for that term. So a single descending loop from D down to M inclusive (where D is the maximum index initially) will reduce all high-degree terms because any newly created term at index i-1 (which may be >= M) will be processed when we get to that index (since we are going downwards). But what if i-1 is > i? It's less, so it will be processed later as we continue decreasing. However, if we modify C[i-1] after we have already passed i-1 in the loop? Since we are descending, we start at D and go down to M. Suppose we process i, and modify C[i-1] (increase it). At that point, we haven't processed i-1 yet because we are at i and then we will go to i-1 next. So it's fine. Now consider we process i, and we modify C[i-M] which is less than i-M, but we will eventually get to index i-M only if i-M >= M. If i-M >= M, then we will process it later (since i-M < i and we are descending). If i-M < M, then it's already in remainder and we don't need to process further. So one descending pass works as long as we have allocated C with enough length to accommodate indices up to D. Since D can be up to 2M-2, and i-M may be >= M for i near 2M-2? For i = 2M-2, i-M = M-2 < M, so fine. So all newly created terms at index i-1 are >= M for i > M, and they will be processed. So one pass is sufficient.
But careful: what about when we process i, and after adding to C[i-1], that could make C[i-1] nonzero. Then when we later process i-1, we will apply the reduction again. This is good. However, what if after processing i, we also add to C[i-M] which could be >= M? As argued, i-M < M for i < 2M? Actually i max = 2M-2 => i-M <= M-2, so < M. So it's safe.
Thus we can implement a function mul(A, B) that returns polynomial C of degree < M (remainder mod Q). Steps:
-
Compute raw product: C_raw = [0] * (len(A)+len(B)-1) (max index = degA+degB). Since both A and B have degree < M, product degree < 2M-2.
-
For i in range(len(A)):
for j in range(len(B)):
C_raw[i+j] = (C_raw[i+j] + A[i]*B[j]) % MOD
-
Reduce C_raw to degree < M using the descending loop:
for i in range(len(C_raw)-1, M-1, -1):
coeff = C_raw[i]
if coeff:
C_raw[i-1] = (C_raw[i-1] + coeff) % MOD
if i-M >= 0:
C_raw[i-M] = (C_raw[i-M] + coeff) % MOD
# C_raw[i] = 0 (optional, as we will discard later)
Then result = C_raw[:M] (i.e., first M coefficients). However, because we might have modified C_raw[i] to 0 only if we set it, but we didn't. We can just after loop, take first M entries; higher entries are effectively zero after reduction? Not exactly: we added to lower indices but did not set C_raw[i] to zero. But we need to ensure that after the loop, entries with index >= M are not used. In the reduction, we are effectively replacing x^i with contributions to lower degrees, but we didn't zero C_raw[i]. If we later take only first M coefficients, the contributions from higher degrees are already added to lower indices, but the original high coefficients remain present if we don't set them to zero. That would cause double counting if we later used those higher indices again? But we are not using them after taking first M. However, during the loop, when we process i, we use the current value of C_raw[i] (which might include contributions from earlier reductions? Actually, if we don't set it to zero after moving its coefficient, later when we process a lower index j that might have been increased from a higher i? But we are only processing each index once from high to low. If we don't zero it, then when we later process a lower index, we might inadvertently consider the original coefficient again? No, because we only process each index exactly once. At the time we process i, we take the current value of C_raw[i] (which includes any contributions from earlier reductions of higher indices). After we add its contributions to i-1 and i-M, we should set C_raw[i] = 0 to avoid it being considered as a term later if we were to process it again (but we won't because we are moving downwards and i is processed only once). However, if we later have a scenario where we might iterate again (like while loop), not zeroing could cause issues. But with one descending pass, after processing i, we move to i-1 and we will not look at i again. So it's okay not to set to zero; it's just garbage but we will discard indices >= M. However, there is a nuance: when we process i-1 later, we might have added to i-1 from processing i. That's fine. But if we don't set C_raw[i] to zero, it doesn't affect processing of lower indices because we are not using it. So we can simply ignore those high indices after loop.
But be careful: the descending loop must use the original length of C_raw; but as we add to C_raw[i-1] and C_raw[i-M], we may increase those coefficients. However, C_raw[i-1] might be at index less than i, which is within the loop range if i-1 >= M. That's okay. But if i-M is also >= M, we might be adding to an index that we have not yet processed? Since i-M < i, and we are moving downwards, we will eventually process i-M (if i-M >= M). In that case, when we later process i-M, we will use its updated coefficient, which includes the added contribution. That is correct. So one pass is sufficient.
But there is a catch: when we add to C_raw[i-M] and i-M is less than M, then we don't need to process it; it's part of remainder.
Thus after the loop, we can take C_raw[0:M] as the reduced polynomial. However, note that there might still be nonzero coefficients at indices >= M? Actually after processing all i from len(C_raw)-1 down to M, we have ensured that for each index >= M, we have transferred its coefficient to lower indices. But if we didn't zero the index, after processing it, the coefficient remains, but we are going to discard them anyway. So final remainder is the first M coefficients (indices 0..M-1). But we must also consider that after processing, some contributions may have been added to indices that are still >= M? For example, suppose M=5 and we process i=7: we add to i-1=6 and i-M=2. 6 >= M, so we added to index 6. But we will later process i=6 (since we are descending). So that is okay. So after the loop completes, any index >= M should have been processed exactly once (when we reached it), and after processing, we have transferred its coefficient away. However, if we didn't set it to 0, it still holds its original value, but we have also added its value to lower indices. So when we later take first M coefficients, we might be missing that the original high coefficient is still present in the array but we discard it; that's fine because its contribution has been added to lower indices. But if we didn't set it to 0, but we have added its value to lower indices, then the total sum of coefficients is now doubled? Actually careful: The transformation should replace the term coeff * x^i with coeff * (x^{i-1} + x^{i-M}). So the coefficient of x^i should be removed, and coefficients of x^{i-1} and x^{i-M} should be incremented. So we must subtract (or zero out) the original coefficient. In our operation, we did:
C[i-1] += coeff
C[i-M] += coeff
We did not set C[i] = 0. If we don't set it to zero, then the term coeff * x^i remains in the polynomial, which is wrong. But we are going to later ignore indices >= M. However, we also added its contributions to lower indices. So if we leave C[i] as is, then the polynomial represented by the array would have an extra term coeff * x^i. But after the loop, we only take first M coefficients. That extra term would be discarded, but its contribution has already been added to lower indices, effectively counting it twice? No, because we are not including index i in the final remainder. But the transformation is meant to replace the high-degree term with lower-degree terms; we must remove the high-degree term. So if we simply add to lower indices and do not subtract from the high-degree term, then when we later discard the high-degree term, we are effectively removing it, which is correct? Let's examine: Initially polynomial is sum_{k} c_k x^k. After we "process" i, if we do:
c_{i-1} += c_i
c_{i-M} += c_i
and then later we set c_i = 0 or discard it, the transformation is correct. If we only add and then discard c_i without zeroing, the net effect is that we have added contributions but also keep the original c_i if we don't discard it. But if we discard the entire high-degree part (indices >= M) after processing, we are effectively setting those coefficients to zero in the final representation. However, during the processing of other high indices, we might be using the values of c_i from the array. In a single descending pass, when we process index i, we read its current value, which may include contributions from higher indices that have already been processed? Actually, higher indices are greater than i. Since we go descending, by the time we reach i, all indices > i have been processed. Those higher indices may have added to i (if i = j-1 or i = j-M for some j > i). So the current c_i includes those added contributions. That is intended: we want to process the total coefficient at i after incorporating all replacements from higher degrees. Then we apply the reduction to that total coefficient, moving it to lower indices. So we must ensure that after we process i, we zero c_i, because we have moved its entire contribution. If we don't zero it, then when we later process a lower index that is, say, i-1, we might not double-count because we won't look at i again. However, consider the final array: after processing all i from high down to M, the coefficients for indices >= M may still be non-zero if we didn't set them to zero. But we are going to discard them. So the net effect is that we have moved their contributions to lower indices, but we also leave them in the high indices; however, we are discarding the high indices, so effectively we have removed them. So the final remainder (first M coefficients) will have received the added contributions, and the high indices are discarded, which is equivalent to zeroing them. So not explicitly zeroing is okay if we ensure that we don't use those values again in the current pass. But there is a subtlety: when we are processing i, we read c_i, then we add to c_{i-1} and c_{i-M}. If we later process i-1, we will read the updated c_{i-1}, which includes the added contribution. That's fine. But if we don't zero c_i, it doesn't affect anything else because we won't read it again. However, what if later in the same loop, we process an index j that is lower than i but we also have a contribution to j from i? That's fine. And after the loop, we discard high indices. So it's acceptable. But caution: if we add to c_{i-M} and i-M >= M, then we will later process that index. That's fine. So we can avoid zeroing to save a few operations, but it's safer to set to zero to avoid accidental bugs. However, since we will later slice to first M, we don't need to zero; but it's fine.
But there is a catch: when we add to c_{i-1}, if i-1 == i? impossible. So it's fine.
Thus reduction can be done in one descending for loop.
Let's test on small example: M=2, C_raw from multiplication: suppose we have polynomial of degree 3: [a0,a1,a2,a3]. We want reduce mod x^2 - x -1. Process i=3: coeff = a3. Then C[2] += a3; C[1] += a3; (since i-M=1). Then we can set C[3]=0. Next i=2: now C[2] includes original a2 + a3. Process: coeff = C[2]. Then C[1] += coeff; C[0] += coeff; set C[2]=0. So after loop, C[0],C[1] hold remainder. That works.
Now, what about if M large? Works.
Thus we can implement polynomial multiplication with reduction.
Now, exponentiation: We'll compute poly result = [1] (i.e., 1) and base = [0,1] (i.e., x). Then for each bit of N (from LSB to MSB): if bit set: result = mul(result, base); base = mul(base, base).
At the end, result is a polynomial of degree < M representing x^N mod Q.
Then compute answer = sum_{i=0}^{M-1} result[i] * f(i) mod MOD, where f(i) are initial values. Since we have f(0)=1, and for i=1..M-1, f(i)=1? Actually f(i)=1 for i from 1 to M-1 as well? Let's verify: For i=0: f(0)=1 (empty composition). For i=1: only composition is "1", so 1. For i=2: if M>2, then only "1+1", so 1. So indeed f(i)=1 for 0 <= i < M? But wait: f(0)=1, f(1)=1, f(2)=1,..., f(M-1)=1. So all ones. Then answer = sum_{i=0}^{M-1} result[i] * 1 = sum(result[i]) mod MOD. But careful: For i=0, f(0)=1. So yes, answer = sum of coefficients of the remainder polynomial. That seems almost too simple. Let's test with M=2: For N=4, we had remainder 2+3x => sum=5. For N=3, remainder? x^3 mod Q: we computed earlier: x^3 = 2x+1? Actually compute: x^3 = (x^2)*x = (x+1)*x = x^2+x = (x+1)+x = 2x+1 => remainder 1+2x, sum=3. So works.
But is it always the case that f(i)=1 for all i<M? For i=0, it's 1. For i between 1 and M-1 inclusive, the only composition using parts 1 and M: since M > i, you cannot use part M, so only composition is i ones. So f(i)=1. Yes. So indeed initial vector is all ones. Thus f(N) = sum_{i=0}^{M-1} coeff_i, where coeff_i are from x^N mod Q.
Therefore, we don't even need to store f(i) separately; we just sum the coefficients of the polynomial remainder.
But wait: check for M=2, f(0)=1, f(1)=1, yes. For M=3, what is f(0)=1, f(1)=1, f(2)=1. So all ones. So answer = sum of coefficients of remainder.
Thus the problem reduces to: given N (up to 1e18) and M (<=100), compute the polynomial R(x) = x^N mod (x^M - x^{M-1} - 1), and output sum of its coefficients mod MOD.
But is the polynomial x^M - x^{M-1} - 1 always the correct characteristic polynomial? Let's verify with M=2: x^2 - x - 1. For M=3: recurrence: f(n)=f(n-1)+f(n-3). The characteristic polynomial: x^3 - x^2 - 1. Is that correct? Let's test with small N, M=3.
Compute f(0)=1, f(1)=1, f(2)=1 (since cannot use 3). f(3) = f(2)+f(0) = 1+1=2. f(4) = f(3)+f(1)=2+1=3. f(5)=f(4)+f(2)=3+1=4. f(6)=f(5)+f(3)=4+2=6. Now compute using polynomial remainder sum. Let's compute x^6 mod (x^3 - x^2 - 1) and sum coefficients.
We'll test: M=3, Q=x^3 - x^2 -1.
Compute powers:
x^0 = 1 -> sum=1.
x^1 = x -> sum=1.
x^2 = x^2 -> sum=1.
x^3 ≡ x^2 + 1 -> remainder: 1 + x^2? Actually x^3 = x^2 + 1 => poly: 1 + 0x + 1x^2? Wait: coefficient: constant 1, x:0, x^2:1. Sum=2. That matches f(3)=2.
x^4 = x * x^3 ≡ x*(x^2+1)= x^3 + x ≡ (x^2+1)+x = x^2 + x + 1 => coeff sum=3 => f(4)=3.
x^5 = x * x^4 ≡ x*(x^2+x+1)= x^3+x^2+x ≡ (x^2+1)+x^2+x = 2x^2 + x + 1 => sum = 2+1+1=4 => f(5)=4.
x^6 = x * x^5 ≡ x*(2x^2+x+1)=2x^3 + x^2 + x ≡ 2*(x^2+1)+ x^2 + x = 2x^2+2 + x^2 + x = 3x^2 + x + 2 => sum = 3+1+2=6 => f(6)=6. Works.
Thus answer = sum of coefficients of remainder.
So we just need to compute the remainder polynomial of x^N modulo the polynomial P(x)=x^M - x^{M-1} - 1, over the ring Z_mod.
Implementation details:
-
Represent polynomials as lists of ints mod MOD, length up to M (after reduction). But during multiplication, we need lengths up to 2M-1.
-
Function mul_mod(A, B):
// both A and B are of length <= M (degree < M)
Compute C = [0]*(len(A)+len(B)-1) // at most 2M-1
for i, ai in enumerate(A):
if ai:
for j, bj in enumerate(B):
if bj:
C[i+j] = (C[i+j] + ai * bj) % MOD
// Reduce C modulo P
for i in range(len(C)-1, M-1, -1):
coeff = C[i]
if coeff:
C[i-1] = (C[i-1] + coeff) % MOD
if i-M >= 0:
C[i-M] = (C[i-M] + coeff) % MOD
# we can set C[i] = 0 if we want, but not needed if we discard later
After reduction, we only need first M coefficients; any beyond are zero (conceptually). But because we didn't set them to zero, we must ensure they are not used. So we take slice:
return C[:M] # if len(C) < M, pad with zeros? Actually if len(C) < M, it means degree < M, no reduction needed; but we still want length M. So we can pad with zeros.
But note: after reduction, the array C may have length less than M? Initially, if len(C) < M, we skip the reduction loop. Then we should still return a list of length M, with zeros for higher degrees. So we can do: result = [0]*M; then copy C[0:min(M, len(C))] into result. Or simpler: after reduction, we take first M entries, but if C is shorter than M, we need to pad. So:
res = [0]*M
for i in range(min(M, len(C))):
res[i] = C[i] % MOD
return res
But note: In the reduction loop, we might modify C[i-1] and C[i-M], but if the list length is not sufficient to hold i-M, we need to ensure that the list is long enough. Since max index i can be up to len(C)-1, and i-M >=0, we need list index i-M exists. Since len(C) is at most 2M-1, i-M <= (2M-2)-M = M-2, which is < M. So list length > i-M because i-M < len(C)? Not necessarily: If len(C)=2M-1, i-M maximum is M-1, which is < len(C). So it's safe.
Also note: When i-M is negative? Only if i < M, but we only loop for i>=M, so i-M >=0. Good.
Edge: M may be 1? But M>=2, so fine.
Now exponentiation:
def poly_pow(N, M):
# compute x^N mod P
result = [1] # polynomial 1
base = [0,1] # polynomial x
while N > 0:
if N & 1:
result = mul_mod(result, base)
base = mul_mod(base, base)
N >>= 1
return result # length M
But careful: result and base initially may not be length M; after each mul_mod they become length M. So we should after each multiplication ensure they are length M.
Now, answer = sum(result) % MOD.
Check for N < M: For N < M, we can compute directly as 1. But does the polynomial method give correct result? Let's test for N=1, M=3. Compute x^1 mod P. Since degree 1 < M, result polynomial is x (coeff: [0,1,0] if length 3). Sum = 1? Actually [0,1,0] sum=1. Good. For N=0? Not needed as N>=1. So the polynomial method works for all N.
But we need to handle large N (1e18) with O(log N) steps, each step mul_mod which is O(M^2) because double loop over coefficients (length M each). Since M <= 100, M^2 = 10000. Number of steps ~ 60, total ~ 600k operations, which is trivial. So we can implement this cleanly.
But we need to be careful about the polynomial representation: length M. In mul_mod, we multiply two polynomials of length at most M. The double loop will iterate over up to M*M = 10k iterations. That's fine. Then reduction loop: iterates over indices from up to 2M-2 down to M, at most M steps, each with constant work. So overall O(M^2) per multiplication.
Thus total operations ~ 60 * (M^2) = 60*10000 = 600,000, plus overhead. Very fast.
Implementation plan:
- Read N, M.
- MOD = 10**9+7.
- If M == 0? Not possible.
- Define function mul(A, B):
A, B are lists of length M (they represent coeffs for x^0..x^{M-1})
Compute product C length up to 2M-1
lenA = len(A) # could be M, but maybe sometimes less? We'll keep as M.
lenB = len(B)
Actually we can assume they are length M; we passed them after previous mul, which always returns length M.
But for initial base [0,1], it's length 2, not M. So we need to handle that. We can simply treat them as lists of coefficients; after each multiplication we return length M. So in mul, we should accept any length but we can treat them as lists; but we can also extend to length M by padding zeros? Simpler: within mul, we don't assume length M. We'll compute raw product based on actual lengths.
But then reduction uses M. So we need M as a parameter.
We'll define mul(A, B, M):
lenA = len(A); lenB = len(B)
C = [0]*(lenA+lenB-1)
for i in range(lenA):
ai = A[i]
if ai:
for j in range(lenB):
C[i+j] = (C[i+j] + ai * B[j]) % MOD
# reduce
for i in range(len(C)-1, M-1, -1):
coeff = C[i]
if coeff:
C[i-1] = (C[i-1] + coeff) % MOD
if i-M >= 0:
C[i-M] = (C[i-M] + coeff) % MOD
# C[i] could be left, but we ignore later
# take first M coefficients
res = [0]*M
limit = min(M, len(C))
for i in range(limit):
res[i] = C[i] % MOD
return res
But note: In reduction, we used C[i-M] which may be beyond the current length if i-M >= len(C)? Since i ranges up to len(C)-1, i-M <= len(C)-1 - M. Since len(C) <= lenA+lenB-1 <= 2M-1, i-M could be up to (2M-2)-M = M-2, which is less than len(C) because len(C) at least M (since i >= M). So safe.
But if len(C) < M, we skip the loop; then we need to pad to length M. That's fine.
Now, exponentiation:
result = [1] # initially 1 polynomial
base = [0, 1] # x
while N > 0:
if N & 1:
result = mul(result, base, M)
base = mul(base, base, M)
N >>= 1
At the end, result is a list of length M. answer = sum(result) % MOD.
But we must be careful about the fact that initial result length is 1, base length 2. That's fine.
Now, test with examples:
Example1: N=4, M=2.
Initialize result=[1], base=[0,1].
N=4 binary: 100.
Step1: N&1=0 => skip result mul.
base = mul(base,base,2). Compute basebase: (x)(x)=x^2. Raw C = [0,0,1]. Reduce: i=2 (>=2): coeff=1 => C[1] +=1, C[0] +=1 (since i-M=0). So after reduction, C becomes [1,1,1? Wait we set C[1] and C[0] but we didn't set C[2] to 0. Our res after taking first M=2: we take C[0] and C[1] = [1,1]? Actually after loop, C[0]=1, C[1]=1, C[2]=1 (but we ignore). So base becomes [1,1]? But that's x^2 mod (x^2 - x -1) which we computed earlier as x + 1. Indeed coefficients [1,1] correspond to 1 + x. Good.
N>>=1 => N=2.
Step2: N&1=0 => skip result mul.
base = mul([1,1],[1,1],2). Multiply (1+x)*(1+x)=1+2x+x^2. Raw C = [1,2,1]. Reduce: i=2: coeff=1 => C[1]+=1 => becomes 3; C[0]+=1 => becomes 2. So C becomes [2,3,1?] Actually C[0]=2, C[1]=3, C[2]=1? Then we take first 2: [2,3] which corresponds to 2+3x. base becomes [2,3].
N>>=1 => N=1.
Step3: N&1=1 => result = mul(result, base). result currently [1] (since unchanged). mul([1], [2,3],2). Raw product: [2,3]. len(C)=2 < M=2? Actually len=2, M=2, loop condition: for i from len(C)-1 (1) down to M (2)? Since M=2, i runs from 1 down to 2? That's empty because 1 < 2. So we skip reduction. Then we take first M=2: pad to length 2? limit = min(2,2)=2, so copy C[0]=2, C[1]=3 -> result=[2,3]. Good.
base = mul(base,base) maybe not needed? But we still compute: base = mul([2,3],[2,3],2) but N becomes 0 after shift, but we still compute base? In loop after checking N&1, we do base = mul(base,base) regardless, then N>>=1. So after N=1 step, we compute base = mul(...) but then N becomes 0, loop ends. It's fine.
Finally result = [2,3], sum=5.
Example2: N=3, M=2.
Start result=[1], base=[0,1], N=3 (binary 11)
Step1: N&1=1 => result = mul([1],[0,1],2) => product raw [0,1], len=2, M=2 => skip reduction, result becomes [0,1]? Actually first M entries: [0,1] (since len=2, we copy both). So result=[0,1].
base = mul([0,1],[0,1],2) => base becomes [1,1] (as earlier).
N>>=1 => N=1.
Step2: N&1=1 => result = mul(result=[0,1], base=[1,1],2) => multiply: (x)*(1+x)= x + x^2. Raw [0,1,1]. Reduce: i=2: coeff=1 => C[1]+=1 -> becomes 2, C[0]+=1 -> becomes 1. So after reduction, C becomes [1,2,1]. Take first 2: [1,2] -> result=[1,2].
base = mul([1,1],[1,1],2) => becomes [2,3] as earlier (but not used).
N>>=1 => N=0.
Result sum = 1+2=3. Good.
Thus works.
Now consider M=100, N large, should be fine.
One more test: N=1, M=100: result sum? f(1)=1. Let's simulate: initial result=[1], base=[0,1]. N=1 binary: LSB=1 => result=mul([1],[0,1],100). raw product length 2? Actually mul: raw C=[0,1]. Since len(C)=2 < M=100, skip reduction, result becomes padded to length 100: [0,1,0,0,...]? In our mul, we take first M entries, but we copy from C. So result[0]=0, result[1]=1, rest 0. Sum = 1. Good.
Now test N=100, M=3? We can test with known recurrence.
Let's compute using Python mental? Not needed.
Now complexity: O(log N * M^2). M=100 => 10k per multiply, times about 60 = 600k. That's trivial. The main loops are Python nested loops; 600k is very fast. However, note that we may perform up to 2log N multiplications (each iteration we do one square and possibly one multiply). For N up to 1e18, log2 about 60, so up to 120 multiplications. That's still 12010k=1.2 million, still very fast.
But in each multiplication, we do a double nested loop over len(A)*len(B). In the worst case, len(A)=len(B)=M=100, so 10k iterations. Each iteration does a multiplication and addition modulo MOD. That's fine.
Edge Cases: M could be 2 to 100; N could be up to 1e18, which fits in Python int.
Potential pitfalls:
- When M is large, but the polynomial base and result may have leading zeros. In mul, we compute product using the actual lengths of A and B. However, if we always pad to length M, there may be many zeros, leading to wasted loops. But we can keep them as length M (with possible trailing zeros? Actually after reduction, we return length M, which may have zeros at high degrees if the polynomial degree is less than M-1. For example, result after initial steps might be [1,0,0,...]. So we have many zeros. In mul, we would still iterate over all MM indices, many of which are zero. To optimize, we could store only non-zero coefficients, but M is small, so it's fine to iterate over all M indices. 100100 = 10000, trivial.
But wait: when A or B have length M but many zeros, the double loop still iterates over all 100*100 = 10000 entries. That's fine. But we can early skip zeros by checking if ai != 0. We already do that. But if many zeros, still we check each ai. Overhead is minimal.
However, note: in our mul function, we treat A and B as lists of length possibly less than M. But after the first multiplication, we always return lists of length M. So after first multiplication, len(A)=len(B)=M. So double loop is always 10k. Good.
Now about reduction: after computing raw product, we loop from len(C)-1 down to M. len(C) can be up to 2M-1 = 199. So at most 100 iterations. That's fine.
Thus overall performance is excellent.
Now we must be careful about the polynomial we reduce modulo: P(x) = x^M - x^{M-1} - 1. In our reduction step, we used the transformation derived from x^M = x^{M-1} + 1. But is that always correct modulo our modulus? Yes, because we are working modulo the polynomial, i.e., we treat x^M ≡ x^{M-1} + 1. So the reduction rule is: for each term with exponent i >= M, replace x^i by x^{i-1} + x^{i-M}. That's what we did. So it's correct.
Double-check for M=2: rule x^2 = x + 1. For i=3: x^3 = xx^2 ≡ x(x+1)=x^2+x ≡ (x+1)+x = 2x+1, which matches our reduction approach: for i=3, we add coeff to i-1 and i-2? Actually i-M =1, so adds to x^1 and x^{i-M}= x^{1}. Wait: i=3, M=2, i-M=1, so we add to x^{i-1}=x^2 and x^{i-M}=x^1. Then later we reduce x^2 similarly. So it's consistent.
Now, think about the initial polynomial P(x) = x^M - x^{M-1} - 1. In modular arithmetic, we consider x^M ≡ x^{M-1} + 1. So the reduction rule is exactly as implemented.
Now, is there any risk of index out of range when i-M is negative? We only loop i >= M, so i-M >=0, safe.
Now, we should also consider the case when M=1? Not possible, but if M=1, the recurrence would be f(n) = f(n-1)+f(n-1)=2f(n-1) with f(0)=1 => f(n)=2^n. But M≥2, so skip.
Now, confirm for large M and N: Our method computes the polynomial remainder for exponent N. The characteristic polynomial is degree M, we are exponentiating modulo that polynomial. This is analogous to computing linear recurrence using binary exponentiation. Works.
Thus final answer = sum of coefficients of that remainder mod MOD.
But we should test for another case: N=5, M=3. We computed earlier f(5)=4. Let's simulate using code mentally? We'll trust.
Now, what about N = M? For M=3, N=3 => f(3)=2. Compute: x^3 mod (x^3 - x^2 -1) = x^2 + 1 (since x^3 = x^2 + 1). Coeff: [1,0,1]? Actually representation: constant 1, x coeff 0, x^2 coeff 1 => sum=2. Good.
Now, check for N = M+1? For M=3, N=4: f(4)=3. x^4 = x*(x^3) ≡ x*(x^2+1)= x^3 + x ≡ (x^2+1)+x = x^2 + x + 1 => sum=3.
All consistent.
Thus we can implement.
But there is a nuance: Our polynomial remainder approach yields the sum of coefficients as f(N) only because initial values are all ones. However, if the initial values were something else, we would need to dot product. Here it's all ones, so sum works.
But we must double-check the definition of f(0). In compositions, the empty composition (0) is often counted as 1 way. In recurrence f(0)=1 works. For N>0, we always have at least one part. So it's fine.
Thus answer = sum coefficients of remainder.
But is it possible that N is 0? Not per constraints, but if N=0, then answer should be 1? Not needed.
Now, let's also consider the alternative combinatorial sum: f(N) = sum_{b=0}^{⌊N/M⌋} C(N - (M-1)b, b). That sum is also valid and we could compute using Lucas or something? But N huge, b up to N/M, not feasible.
Thus polynomial exponentiation is the way.
Now, I'll write the code.
Potential pitfalls:
- We must use modulo 1000000007.
- When reducing, we must do modulo after each addition.
- In mul, after the reduction loop, we take first M coefficients. However, note that during reduction we may have added to indices beyond M? Actually we only added to indices i-1 and i-M, both less than i. Since i <= len(C)-1, and we only add to indices within range because i-1 and i-M are >=0 and < len(C) (since i-M <= i-1 < i <= len(C)-1). So they are within C. But when we later take C[:M], we are only taking indices 0..M-1. The contributions to indices >= M (i-1 may be >= M) will be lost if we don't process them further. But we did process them: we processed all i >= M in descending order. When we added to index i-1 which is >= M, we will eventually process that index when the loop reaches i-1. So by the time we finish the loop, all contributions have been propagated to indices < M. But what about contributions to index exactly M? In the loop, we process i from len(C)-1 down to M. When i = M, we process it. So if we add to index i-1 = M-1 (which is < M), that's fine. And if we add to i-M which is 0, that's < M. So no contributions remain at indices >= M after the loop if we properly process them? But we didn't set C[i] to zero, so after processing i, C[i] still has its original coefficient. But as argued, after we finish the loop, indices >= M may still have non-zero values because we didn't zero them. However, the contributions from those indices have already been moved to lower indices, but the original values are still present. If we then take only first M entries, we are discarding those high indices, which effectively removes them. But is it correct to just discard them? Since we have already added their contributions to lower indices, we need to ensure we are not double counting. The polynomial after reduction should have zero coefficients for degrees >= M. In our method, we have not explicitly set them to zero. If we discard them, we are effectively setting them to zero. But does the presence of the original value in those indices affect the lower indices? No, because we already used them to add to lower indices. However, if we later used C[i] again (which we don't), it's fine. So final remainder is just the first M coefficients. The original high coefficients are not part of the remainder because we discard them. So that's correct.
But there is a subtlety: Suppose we have a coefficient at index i that we process. We add its value to lower indices. Then later, when we process a lower index j that receives some addition, we use its updated value to further reduce if j >= M. That's correct. But if we do not zero C[i], then later if some other operation (like another multiplication) uses that C[i] again? No, after the reduction we are done. So it's fine.
However, there is a scenario: In the reduction loop, when we go from high to low, we read C[i] at each step. If we have already added to C[i] from processing a higher index, then we correctly include that in the reduction. Good.
Thus the method is correct.
One more nuance: In the reduction loop, we loop for i in range(len(C)-1, M-1, -1). But what if after processing a high i, we add to C[i-1] which is >= M, and then later when we get to i-1, we will process it. However, we also add to C[i-M] which may also be >= M if i-M >= M. For i up to 2M-2, i-M max is M-2 < M. So it's never >= M. So no issue.
Thus it's correct.
Now, we need to ensure that after reduction, we also need to consider that the polynomial may have degree less than M-1 but with leading zeros. Our result list of length M may have zeros at the end; sum works.
Now, test with M=2, N=0? Not needed.
Now, we might also consider using exponentiation by squaring on the matrix, but this polynomial method is simpler and faster.
Thus final answer: implement solve() reading N, M, compute via polynomial exponentiation.
But we must be careful: The polynomial exponentiation method computes x^N mod (x^M - x^{M-1} - 1). However, this relies on the recurrence f(n) = f(n-1) + f(n-M). But is it valid for all n? Yes.
But we must confirm that the characteristic polynomial is indeed x^M - x^{M-1} - 1 and not x^M - x^{M-1} - ...? It is, because coefficients: f(n) = 1f(n-1) + 0f(n-2) + ... + 0f(n-M+1) + 1f(n-M). So yes.
Thus code.
Now, I'll code solve().
Pseudo-code:
MOD = 1000000007
def mul(A, B, M):
# A, B lists of coefficients (length may be <= M, but after first mul we keep them length M)
lenA = len(A)
lenB = len(B)
C = [0] * (lenA + lenB - 1)
for i in range(lenA):
ai = A[i]
if ai:
for j in range(lenB):
bj = B[j]
if bj:
C[i+j] = (C[i+j] + ai * bj) % MOD
# reduction
for i in range(len(C)-1, M-1, -1):
coeff = C[i]
if coeff:
# add to i-1
C[i-1] = (C[i-1] + coeff) % MOD
# add to i-M
if i-M >= 0:
C[i-M] = (C[i-M] + coeff) % MOD
# C[i] will be ignored
# take first M coefficients
res = [0] * M
limit = min(M, len(C))
for i in range(limit):
res[i] = C[i] % MOD
return res
def solve():
import sys
N, M = map(int, sys.stdin.read().split())
if M == 0: # not possible
print(1)
return
if N == 0: # not in constraints but handle
print(1)
return
# compute polynomial remainder of x^N mod (x^M - x^{M-1} - 1)
result = [1] # polynomial 1
base = [0, 1] # polynomial x
# Make base length M? Not needed, mul will handle.
exp = N
while exp > 0:
if exp & 1:
result = mul(result, base, M)
base = mul(base, base, M)
exp >>= 1
# result is list length M
ans = sum(result) % MOD
print(ans)
But note: In mul, when we do base = mul(base, base, M), base becomes length M. Then subsequent multiplications involve length M lists.
Now test with given examples.
Now, could there be any overflow? Python int handles big integers, but we take mod.
Now, let's test with M=100, N large. Should be fine.
Now, confirm that the polynomial method yields f(N) even for N < M? Yes. For N=1, M=100, result becomes [0,1,0,...,0] sum=1.
Now, check for M=2, N=1: base case, correct.
Now, what about N=2, M=3? f(2)=1. Our method: compute x^2 mod (x^3 - x^2 -1) => degree 2 < 3, so remainder is x^2 (coeff [0,0,1] sum=1). Good.
Now, finalize.
Potential improvement: We could also handle the case N < M directly: print 1. But our method works anyway.
Now, we need to ensure that the polynomial reduction works when M is larger than the length of C. In mul, when we compute C, its length could be less than M (if both A and B are short). Then we skip the reduction loop because condition i from len(C)-1 down to M-1 includes only i >= M; if len(C)-1 < M, loop is empty. Then we pad to length M. That's fine.
Now, but there is a nuance: if len(C) < M but we have a term with exponent >= M? Not possible because max exponent = lenA+lenB-2 < M if both lengths are small enough that sum of degrees < M. That's fine.
Now, we should also consider if M is large and N is huge, the exponentiation loop will do around 60 iterations. The multiplication function will be called about 2*log2(N) times, ~120. Each multiplication O(M^2). So fine.
Now, edge case: M=100, N=1e18, no problem.
Now, what about the possibility of using DP with matrix exponentiation? We already have polynomial.
Thus final solution.
But let's double-check the recurrence with another test: M=5, N=5. f(0..4)=1 each. f(5) = f(4)+f(0)=1+1=2. So answer should be 2. Let's manually compute with our method? Quick: x^5 mod (x^5 - x^4 - 1) => x^5 = x^4 + 1 => remainder = x^4 + 1 => coeff: [1,0,0,0,1] sum=2. Yes.
Now, N=6, M=5: f(6)=f(5)+f(1)=2+1=3. x^6 = x * x^5 ≡ x*(x^4+1) = x^5 + x ≡ (x^4+1)+x = x^4 + x + 1 => sum=1+1+1=3.
Works.
Thus answer is correct.
Now, finalize code.
But we might need to handle N=0? Constraints say N>=1, but maybe test includes? I'll just handle N==0 => 1.
Now, one more thought: Could there be any off-by-one in the recurrence? Let's verify with M=2, N=0 (if allowed) => f(0)=1 (empty composition). That's consistent with our base.
Now, about the note: They list configurations with "first magic gem splits" etc. The compositions method matches.
Thus final answer.
Now, we should also think about the scenario where M > N and M maybe > 100? M up to 100 anyway. So fine.
Now, I'll write final solution.
Potential optimization: In mul, we can precompute the indices for reduction? Not needed.
Now, code with careful modular operations.
I'll also add a fast path: if M > N: print(1) directly? Not necessary but could save a few steps. But it's okay.
Now, I will produce the final answer.
Let me write final solution in Python:
def solve():
import sys
MOD = 1000000007
data = sys.stdin.read().strip().split()
if not data:
return
N = int(data[0]); M = int(data[1])
if M == 0: # not possible
print(1)
return
if N == 0:
print(1)
return
# define mul
def mul(A, B, M):
lenA = len(A)
lenB = len(B)
C = [0] * (lenA + lenB - 1)
for i in range(lenA):
ai = A[i]
if ai:
for j in range(lenB):
bj = B[j]
if bj:
C[i+j] = (C[i+j] + ai * bj) % MOD
# reduction modulo x^M - x^{M-1} - 1
for i in range(len(C)-1, M-1, -1):
coeff = C[i]
if coeff:
C[i-1] = (C[i-1] + coeff) % MOD
if i - M >= 0:
C[i-M] = (C[i-M] + coeff) % MOD
# take first M coefficients
res = [0] * M
lim = min(M, len(C))
for i in range(lim):
res[i] = C[i] % MOD
return res
result = [1] # polynomial 1
base = [0, 1] # polynomial x
exp = N
while exp:
if exp & 1:
result = mul(result, base, M)
base = mul(base, base, M)
exp >>= 1
ans = sum(result) % MOD
print(ans)
if name == "main":
solve()
Now, we should test with given examples:
Example1: 4 2 => 5
Example2: 3 2 => 3
We can also test with a few more:
Input: 5 3 => expected? f(5)=4. Let's test manually: Using recurrence: f0=1,f1=1,f2=1,f3=2,f4=3,f5=4 => answer 4. Our code should output 4.
Input: 1 100 => 1.
Input: 100 2 => That's large Fibonacci? Actually f(N) for M=2 is Fib(N+1). So f(100)=Fib(101) mod 1e9+7. Could test but trust.
Now, verify code with some random small values using brute force to ensure correctness. For small N and M, we can compute compositions by DP to compare. But we trust.
One more edge: M=100, N=1. Our code: result initial [1]; base [0,1]; N=1 => result = mul([1],[0,1],100). In mul, lenA=1,lenB=2, C = [0,1] (len=2). Loop for i from len(C)-1=1 down to M-1=99? That's empty because 1<99. So we take res length 100: copy C[0]=0, C[1]=1, others 0. sum=1. Good.
Now, M=100, N=99: expected 1. Let's test quickly: exponent 99, we compute x^99 mod polynomial of degree 100. Since degree less than 100, it remains x^99, sum of coefficients? Actually polynomial x^99 has coefficient 1 at degree 99, others 0. Sum = 1. So answer 1. That's correct.
Now, M=100, N=100: f(100)=f(99)+f(0)=1+1=2. So answer 2. Our code should compute x^100 mod Q. Since x^100 = x^0? Actually using recurrence, should get sum 2.
Now, we should ensure that the reduction step works correctly for high degrees. In mul, when we multiply two polynomials of degree < M, product degree < 2M-2, so max i = 2M-2. Then reduction uses rule. For M=100, max i=198. That's fine.
Now, let's consider potential overflow in the product: ai*bj can be up to (MOD-1)^2 ≈ 1e18, which fits in Python int (unlimited), but we mod after addition.
Now, everything seems fine.
However, one more nuance: In the reduction loop, after we add coeff to C[i-1] and C[i-M], we do not set C[i] to zero. But suppose we have a situation where we later process an index j that is less than i but we might have added to C[i-1] which is >= M, and we will process it. But we also have the original C[i] still there. Since we are iterating descending, after processing i, we will not revisit i. So that's fine. However, if we later in the same loop come to index i-1, we will read the updated C[i-1] which includes the added contribution. That's correct. But what about the original C[i]? It remains, but it's not used again. So it's effectively discarded. So after the loop, if we were to look at C[i] (i>=M), they may still have non-zero values. But we ignore them. So final remainder from the first M coefficients is correct. But is there any chance that some contribution to indices >= M is lost because we never processed them after they were added from a higher index? Let's simulate: We process i, add to C[i-1] (which may be >= M). This addition is included because we will process i-1 later. When we later process i-1, we will take its coefficient (which includes this addition) and reduce it further. Good. So all contributions eventually propagate down to < M. So final first M coefficients contain the full remainder.
Thus algorithm correct.
Now, could we further simplify? Since answer = sum of coefficients of x^N mod (x^M - x^{M-1} - 1), we could also compute using matrix exponentiation on the state vector of size M directly: but our method is simpler.
Now, confirm with another approach: we could compute f(N) by DP using linear recurrence exponentiation via matrix exponentiation on companion matrix, then sum the first row of the matrix times initial vector? But our polynomial method is essentially that.
Now, final code as above.
But there's a potential bug: When M=2, base after squaring becomes [1,1] as we saw. That's correct. For M=3, let's test a step: base = [0,1,0] (if we padded to length 3? Actually initial base is [0,1] which length 2. In mul, after first squaring, we will get base length 3. Let's simulate quickly: M=3, base = [0,1] (x). mul(base,base,3): product: [0,0,1]. len=3. Reduction: i from 2 down to 3? Since M=3, i from 2 down to 3 => empty because 2<3. So we pad to length 3: res = [0,0,1]? Actually we take first M=3, so copy C[0]=0, C[1]=0, C[2]=1 -> base becomes [0,0,1]. That's x^2, which is correct because degree <3. Next, base = mul([0,0,1],[0,0,1],3): product: convolution: degree 4? Actually [0,0,1] * [0,0,1] gives [0,0,0,0,1]? Wait: indices: A indices: 0->0,1->0,2->1. B same. So C[4] gets 1. So C = [0,0,0,0,1] (len=5). Reduction: i from 4 down to 3? M=3, i from 4 down to 3 includes i=4 and i=3? Actually range(len(C)-1, M-1, -1) = range(4,2,-1) gives i=4,3? M-1=2, so includes 4 and 3. i=4: coeff=1 -> C[3] +=1; C[1] +=1 (since 4-3=1). So C becomes: index 3:1, index 1:1, others: originally 0. Now C[4] remains 1 but we ignore? Actually we didn't set C[4] to 0. Then i=3: coeff = C[3] which is now 1 -> C[2] +=1; C[0] +=1 (since 3-3=0). So after i=3: C[2] becomes 1, C[0] becomes 1, and C[3] we don't change? but we didn't zero C[3]. So after loop, C may have values: index0=1, index1=1, index2=1, index3=1 (from earlier), index4=1. But we take first M=3: indices 0,1,2 => [1,1,1]. That corresponds to polynomial 1 + x + x^2. That should be x^4 mod (x^3 - x^2 - 1)? Let's compute manually: x^4 = xx^3 ≡ x(x^2+1)= x^3 + x ≡ (x^2+1)+x = x^2 + x + 1. Yes, remainder is 1 + x + x^2, coefficients [1,1,1]. Good. So our method gave correct result despite not zeroing high indices. So it's fine.
Thus code is correct.
Now, we can also implement a small optimization: Instead of returning a list of length M with possibly many zeros, we could keep only non-zero up to highest degree, but not necessary.
Now, we need to consider potential pitfalls with Python recursion? We're not using recursion.
Now, I'll produce final answer.
But before finalizing, let's check the note again: They considered configurations where the indices of gems to split differ. In our interpretation, the order matters (since composition order matters). That matches the note.
Thus answer is number of compositions.
Now, let's think about potential alternative interpretation: Could the gems be considered unlabeled? That would yield different counts. For example, if order didn't matter, the number of ways to have total space 4 with M=2 would be: possibilities: 4 unsplit (1 way), 2 unsplit + 1 split? That would be 2 unsplit magic + 1 split magic (which yields 2 normal) gives total: 2 magic + 2 normal = 4 gems. But if order doesn't matter, then the multiset {magic, magic, normal, normal} is just one configuration. Plus {4 magic}, {4 normal}, and maybe {magic, magic, magic? No, that sums to 3. So only 3 configurations. But example says 5, so order matters.
Thus our interpretation is correct.
Now, finalize code.
But note: The problem statement says "the indices of gems Reziba has to split differ." That suggests that magic gems are distinguishable (by index), and the order in which they appear might be the order of selection? It matches composition where we have an ordered list of chosen magic gems; splitting decisions are indicated by which positions are split. So composition enumerates all sequences of decisions (split/not) for a sequence of magic gems. The number of magic gems chosen (k) can vary; for each k, the decisions that yield total N correspond to sequences of length k of 1 or M that sum to N. That's exactly compositions.
Thus final solution is correct.
Now, time to produce final answer.
I'll output the Python code.
But I might want to add a fast path: if M > N: answer = 1. Actually for N<M, f(N)=1. So we could early return 1. However, our polynomial exponentiation would compute correctly anyway; but it would do O(log N) multiplications with M up to 100. That's still fine. But maybe we can save a little for N=1e18 and M=100? M not > N because N is huge, so no.
But if N is small like 1 and M=100, our method does about 60 multiplications? Actually N=1, the while loop runs once (since exp=1): first iteration: exp&1 => result = mul([1],[0,1],100); base = mul([0,1],[0,1],100); exp>>=1 =>0. So it does two multiplications: one for result, one for base. That's fine. So no need for early exit.
Now, check for N=0 (not allowed). So fine.
Now, we need to ensure that mul function works when M is 1? But M>=2 so fine.
Now, final answer.
But let me test with a random small case manually via brute force code to be thorough.
Write a small brute for N<= maybe 10 and M=2..5, compute compositions count. But I trust.
Now, before final, I'll think about alternative approach: using matrix exponentiation directly, but it's fine.
Now, produce final answer.
One more nuance: In the reduction loop, we used condition if coeff: to skip zero. That's fine.
But we should also consider that after we add to C[i-1] and C[i-M], these may exceed MOD, we mod them.
Now, what about when i-M is negative? Not possible.
Now, final code.
But we could also simplify by noting that result = sum of coefficients = evaluate polynomial at x=1. Since we have x^N mod (x^M - x^{M-1} - 1). Evaluating at x=1 gives 1^N = 1 mod polynomial? Not straightforward because polynomial modulo changes evaluation? Actually if we evaluate remainder R(x) at x=1, we get R(1). But note that because the modulus polynomial Q(1) = 1 - 1 - 1 = -1, not zero, so x=1 is not a root. So R(1) is not equal to 1^N mod something. But we are summing coefficients, which is R(1). And we also have f(N) = sum_{i=0}^{M-1} f(i) * coeff_i. Since f(i)=1, f(N)=R(1). So answer = R(1). But we are already summing coefficients.
Thus another perspective: f(N) = the value of the linear recurrence with initial ones, which is essentially the N-th term of the sequence defined by a_n = a_{n-1} + a_{n-M} with a_0...a_{M-1}=1. So we can compute that by exponentiation.
Now, I'll finalize.
Now, potential integer overflow? In Python it's fine.
Now, we must ensure that for large M (100) and large N (1e18), the number of multiplications is about 60. However, each multiplication's double loop is over M^2 = 10k. So total 600k operations, very fast. But we also have about 120 calls to mul, each 10k => 1.2 million. That's still trivial.
Thus code will run quickly.
Now, write final solution.
But I want to test with a sample: N=10^18, M=100. That will just compute quickly.
Now, consider potential recursion depth? None.
Now, produce final answer.
But I recall that for M up to 100, the matrix exponentiation approach might be simpler, but we have polynomial.
Now, any pitfalls with reading input? Use sys.stdin.read().
Now, final.
Let me write the final answer in the required format.
Now, I'll produce final ChatGPT response. ```python
import sys
MOD = 1_000_000_007
def multiply(A, B, M):
"""Multiply two polynomials A and B (coeff. lists) and reduce
modulo x^M - x^{M-1} - 1. Returns a list of length M."""
lenA, lenB = len(A), len(B)
# raw product, degree <= lenA+lenB-2
C = [0] * (lenA + lenB - 1)
for i in range(lenA):
ai = A[i]
if ai:
for j in range(lenB):
bj = B[j]
if bj:
C[i+j] = (C[i+j] + ai * bj) % MOD
# reduction using x^M = x^{M-1} + 1
for i in range(len(C)-1, M-1, -1):
coeff = C[i]
if coeff:
C[i-1] = (C[i-1] + coeff) % MOD
if i - M >= 0:
C[i-M] = (C[i-M] + coeff) % MOD
# C[i] is now irrelevant (will be discarded)
# take only coefficients for degrees 0..M-1
res = [0] * M
lim = min(M, len(C))
for i in range(lim):
res[i] = C[i] % MOD
return res
def solve() -> None:
data = sys.stdin.read().strip().split()
if not data:
return
N = int(data[0])
M = int(data[1])
# polynomial representing 1
result = [1]
# polynomial representing x
base = [0, 1]
exp = N
while exp:
if exp & 1:
result = multiply(result, base, M)
base = multiply(base, base, M)
exp >>= 1
# answer = sum of coefficients of result (all initial values are 1)
ans = sum(result) % MOD
print(ans)
if name == "main":
solve()