We need to understand problem: Initially there are n species with counts a_i. After each day j, a new species with count c_j is added. So total number of species after t days = n + t. For each day we need to consider all subsets of exactly k species from the current set of species, compute the maximum number of gardens possible for that subset, then sum those maximum numbers across all subsets. Output sum modulo MOD=1e9+7.
For a given subset of k species with counts v1, v2, ..., vk, we need to find maximum number g of identical gardens (each garden gets equal number of each species) such that each garden uses some integer number of each flower. Since gardens identical, let per garden we use x_i flowers of species i, and total gardens = g. Then g * x_i = v_i, so x_i = v_i / g must be integer. So g must be a common divisor of the k counts. The maximum possible g is gcd(v1, v2, ..., vk). So the max number of gardens = gcd of the counts of the selected species.
Thus for each subset S of size k, we need to compute gcd of its elements, and sum those gcd's.
So problem: For a multiset of numbers (initial counts + added counts), after each addition, compute sum_{S subset of current set, |S|=k} gcd(S). Where gcd(S) denotes GCD of numbers in S.
We need to do this for up to N = n + q <= 200,000 (since n,q up to 100k) numbers, each up to 1e6. We need to output after each addition, total sum modulo 1e9+7.
Brute force over subsets impossible. Need to compute combinatorial sum of gcd over subsets.
We need to compute F = sum_{S, |S|=k} gcd(S). For dynamic additions: we insert numbers one by one. Possibly we can maintain some structure that supports adding a number and updating the sum efficiently.
Observations: The numbers are up to 1e6, so we can use divisor-based counting. Typically, for fixed set of numbers, sum_{S} gcd(S) can be expressed in terms of number of subsets whose gcd is divisible by d, using Mobius inversion.
Let f(d) = number of subsets of size k such that the gcd of the subset is exactly d. Then answer = sum_d d * f(d). We could also define g(d) = number of subsets of size k where all numbers in subset are multiples of d. Then by inclusion-exclusion, f(d) = g(d) - sum_{multiple m> d} f(m) if we want exact, but we can use Mobius: f(d) = sum_{m: d|m} μ(m/d) * g(m). Actually typical: let G(d) = number of subsets of size k where all elements are divisible by d. Then the number where gcd exactly d is F(d) = G(d) - sum_{i>=2} F(id). Using Mobius: F(d) = sum_{t>=1} μ(t) G(dt). Then answer = sum_d d * F(d) = sum_d d * sum_{t} μ(t) G(d*t) = sum_{m} G(m) * (sum_{d|m} d * μ(m/d) )? Let's derive.
We have G(m) = number of subsets (size k) with all numbers divisible by m. Let cnt_m = number of numbers in the whole set that are multiples of m. Then G(m) = C(cnt_m, k) if cnt_m >= k else 0.
We want answer = sum_{S} gcd(S) = sum_{d} d * F(d) where F(d) exact gcd.
But we can also write directly: gcd(S) = sum_{d | gcd(S)} φ(d)? Actually there is identity: gcd(a1,...,ak) = sum_{d|gcd} φ(d) ? Not exactly; there is ∑{d|gcd} φ(d) = gcd, because Euler's totient sum over divisors of n equals n. Yes: n = ∑{d|n} φ(d). So gcd(S) = ∑{d | gcd(S)} φ(d). Then sum over subsets S of gcd(S) = ∑{S} ∑{d | gcd(S)} φ(d) = ∑{d} φ(d) * (number of subsets S such that d divides all elements of S) = ∑{d} φ(d) * C(cnt_d, k). Because for a given d, the condition d|gcd(S) means d divides every element in S, i.e., all chosen numbers are multiples of d. So number of subsets of size k with all numbers multiples of d is C(cnt_d, k). So answer = ∑{d} φ(d) * C(cnt_d, k). Where cnt_d = count of numbers in the current set that are multiples of d.
That's a very nice formula! Let's verify: For any subset S, gcd(S) = ∑{d|gcd(S)} φ(d). Then sum over S = ∑{d} φ(d) * #{S : d | all elements of S} = ∑_{d} φ(d) * C(cnt_d, k). Indeed, provided we consider d up to max value (1e6). This is standard technique.
Thus, after each insertion of a new number x, we need to update cnt_d for all divisors d of x, and recompute total sum = ∑_{d} φ(d) * C(cnt_d, k) modulo MOD. Since we only need to update when cnt_d changes (increases by 1 for divisors of x). The contribution for each d is φ(d) * (C(cnt_d, k) - C(cnt_d-1, k)) when cnt_d increments by 1. So we can maintain current sum, and for each divisor d of x, before updating cnt_d, we subtract old contribution (C(cnt_d, k) maybe we store current cnt_d) and then add new after increment. However, careful: When we increment cnt_d, the contribution to total sum from divisor d becomes φ(d) * C(cnt_d, k). So delta = φ(d) * (C(cnt_d, k) - C(cnt_d-1, k)). So we can update sum = sum + φ(d) * deltaC.
Thus per insertion, we need to iterate over all divisors d of x (up to ~240 for numbers <=1e6? Actually max divisors is around 240 for numbers <=1e6, I think ~240 for 720720? Actually number of divisors for numbers up to 1e6 is at most 240 (e.g., 720720 has 240 divisors? That number is 720720 > 1e6? 720720 = 2^43^25711*13, I recall it's around 1e6 and has 240 divisors; but within 1e6, maximum divisor count is 240 (for 997920 maybe). So average around 100. So iterating divisors per insertion is okay: q up to 100k, total divisor iterations ~ 2e7, which is okay in C++ but maybe heavy in Python? We need to implement in Python? The problem is from Codeforces? Usually C++ expected but we can try Python with optimizations. However given constraints up to 1e5 insertions and each number up to 1e6, iterating over divisors for each insertion in Python might be borderline but likely okay with precomputed smallest prime factors (SPF) to factorize and generate divisors efficiently. Also we need to compute φ(d) for each divisor. Could precompute φ for all numbers up to 1e6 via sieve.
Also we need to compute binomial coefficients C(cnt, k) mod MOD. But cnt_d can be up to total numbers (N <= 200k). k is fixed, up to n <= 100k. So we need to compute C(m, k) for many m values (each cnt_d changes). Since we need to compute C(cnt, k) and C(cnt-1, k) for each increment. We can maintain factorials and inverse factorials up to N (200k) to compute combinations quickly O(1) per query. However we need to compute many times: each divisor update requires computing C(cnt, k) and C(cnt-1, k). Since cnt_d can be at most N. So we can precompute factorials and inv factorials mod MOD for N_max = n+q up to 200k. Then C(m, k) = fact[m] * inv_fact[k] * inv_fact[m-k] % MOD, provided m >= k, else 0.
But note: cnt_d can exceed N? No, total numbers is N. So max m is N. So factorial up to N is fine. However we also need to compute C(cnt, k) for cnt that might be less than k; in that case contribution 0.
But careful: After each insertion, many cnt_d will increase; we need to compute deltaC = C(cnt+1, k) - C(cnt, k) for each divisor. However computing both combinatorics per divisor could be O(1) each with precomputed factorials. That would be acceptable: total divisor operations ~ 2e7, each doing a few multiplications/mod operations (with Python ints mod 1e9+7), might be okay if optimized. But 2e7 operations in Python might be borderline but possible if well optimized (maybe ~0.2-0.5 seconds per 10 million? Actually Python loops over 20 million can be 1-2 seconds? Might be okay within typical 2-4 sec? But problem may have time limit 2-3 seconds, Python might be too slow. But we can try to optimize: precompute φ for all up to maxV = 1e6; precompute divisors for each number? That would be too much memory (1e6 * avg divisors ~ 1e8). Not possible. So we need to generate divisors on the fly via prime factorization using SPF. That adds cost: factorization for each x (which up to 1e6) involves dividing by primes until sqrt, but with SPF it's efficient: while x > 1: p = spf[x], exponent, then produce divisors. That is also moderate.
But we need to compute deltaC quickly. We'll maintain an array cnt[d] for all d up to maxA (max value of any a_i or c_j). maxA = 1e6. So we need an integer array of length 1e6+1. That's okay (1e6 ints, ~8 MB). We'll also need to precompute φ[1..maxA] (int array). Also factorials up to N_max (200k). So memory is fine.
But we also need to consider the initial n numbers: we need to process them as initial insertions. So overall we have N_total = n + q insertions. However we need to output after each of the q days (i.e., after each new species added). But initial n are present from the start, so before any query we need to compute initial sum based on initial n numbers. Then for each new number c_j, update sum and output after update.
Thus we can treat it as: start with empty set, then insert all initial n numbers (we could compute initial sum by processing them as insertions), then output after each subsequent insertion? Wait, the problem says: "After receiving flowers on each of these q days, Farmer John would like to know the sum...". That means after each day, we consider the set that includes the initial n species and the newly added ones so far. So we need to output after each addition. So we need to compute initial sum for the set of size n, then for each new number, update and output.
Thus we can process initial numbers as insertions to build cnt array and compute sum_initial. Then for each day j from 1 to q, read c_j, update, output.
Now, complexity: For each insertion (including initial n), we factorize x (max 1e6) and iterate over its divisors. Total insertion count = n+q <= 200k. Divisor enumeration per number: if we use prime factorization and generate divisors recursively, the number of divisors is small (~ <200). So total divisor visits ~ 200 * 200k = 40 million. That's a lot for Python maybe borderline but perhaps acceptable if we code efficiently and use PyPy. 40 million operations of moderate complexity (array lookups, modular arithmetic) could be okay in PyPy within 3-4 seconds? Might be close. But we can attempt to optimize: precompute φ(d) for all d; store cnt array as ints; compute factorials and inv factorials; compute binom quickly.
But we also need to compute the deltaC = C(cnt+1, k) - C(cnt, k). This can be computed using formula: if cnt < k-1, then C(cnt+1,k) = 0 and C(cnt,k)=0? Actually if cnt+1 < k then both 0; if cnt+1 == k then C(cnt+1,k)=1 and C(cnt,k)=0; etc. But we can compute using factorial precomputation. However factorial precomp only goes up to N_total (max cnt). Since N_total <= 200k, factorial array length 200001, which is fine.
But we need to compute inv_fact as well. Precompute them.
Now we need to compute C(m, k) quickly. Since k is fixed, we could precompute all C(m, k) for m from 0 to N_total using recurrence: C(m, k) = C(m-1, k) * m / (m-k) if m > k; but using modular inverse would require division. However using factorial is O(1) each.
We could also precompute an array comb_m = C(m, k) for m = 0..N_total, which we can compute iteratively: comb[0] = 0 (if k>0), ... Actually we can compute comb[m] = fact[m]*inv_fact[k]*inv_fact[m-k] % MOD for each m. That would be O(N_total) precomputation, which is okay (200k). Then during updates we just look up comb[cnt] and comb[cnt-1] from precomputed array. This avoids computing factorial multiplication each time. Since we have many queries (up to 40 million lookups), having precomputed comb array would be faster: array of size N_total+1 (maybe up to 200k). But cnt_d can be up to N_total. However some cnt_d might be for d that are divisors, but cnt_d could be large? Yes, cnt_d can be up to N_total, which is 200k. So we need comb array of size N_total+1. That is fine. Also for cnt_d < k, comb=0. So we can precompute comb[0..N_total] where comb[m] = C(m, k) if m >= k else 0. That array is about 200k integers. Then deltaC = comb[cnt+1] - comb[cnt] mod MOD? Actually careful: When we increment cnt_d from old = cnt to new = cnt+1, the new contribution is φ(d)*comb[new] and old was φ(d)comb[old], so delta = φ(d)(comb[new] - comb[old]) mod MOD. So we can compute diff = comb[new] - comb[old] (taking mod). So we need to store comb for all m from 0 to N_total.
Thus, per divisor we do:
- old_cnt = cnt[d]
- new_cnt = old_cnt + 1
- diff = comb[new_cnt] - comb[old_cnt] # could be negative, adjust mod
- sum = (sum + phi[d] * diff) % MOD
- cnt[d] = new_cnt
That's a few array accesses and arithmetic.
Now, we also need to compute divisors of x. We'll precompute SPF (smallest prime factor) up to maxA = 1e6 using sieve O(maxA log log maxA). Then for each x, factorize using SPF to get prime factorization as list of (p, exp). Then generate all divisors recursively (or iteratively). The number of divisors is small, so recursion overhead might be okay. But we can also generate divisors iteratively: start with [1]; for each p^e, multiply existing divisors by p^exp for exp from 1..e. This is typical.
Alternatively, we could precompute list of divisors for all numbers up to 1e6 using sieve-like method: for d from 1 to 1e6, for multiple m of d, add d as divisor? But that would require O(maxA log maxA) time and memory to store lists; memory huge (sum of divisor counts up to 1e6 ~ 14 million? Actually sum_{i=1}^{N} d(i) ~ N log N, for N=1e6, sum ~ 14e6, storing them as list of lists might be heavy but could be done (14 million ints, maybe okay, but each list overhead huge). Better generate on the fly.
So overall algorithm:
- Read n, k, q.
- Read initial a_i (n numbers) and queries c_j (q numbers). (Maybe store all to process sequentially, but we need to output after each query.)
- Precompute maxVal = max(max(a_i), max(c_j)) up to 1e6. Also total numbers N_total = n+q.
- Precompute phi[1..maxVal] using linear sieve or Euler's totient sieve.
- Precompute SPF for numbers up to maxVal.
- Precompute factorials and inv factorials up to N_total. Actually N_total may be up to 200k. So compute fact[0..N_total], inv_fact similarly.
Or directly precompute comb[0..N_total] = C(m, k) if m>=k else 0.
We'll compute comb using factorials: comb[m] = fact[m] * inv_fact[k] % MOD * inv_fact[m-k] % MOD if m>=k else 0.
- Initialize cnt array of size maxVal+1 to zeros.
- Initialize total_sum = 0.
- Process initial n numbers: for each x in a_i, call add(x) which updates cnt and total_sum.
add(x):
get divisors list of x.
for each d in divisors:
old = cnt[d]
new = old+1
diff = comb[new] - comb[old] (if old < 0? but old >=0)
total_sum = (total_sum + phi[d] * diff) % MOD
cnt[d] = new
- After processing initial, we haven't output anything yet.
- For each query c_j (j=1..q):
add(c_j) (as above)
print total_sum % MOD (ensuring positive).
We need to ensure modulo operations: phi[d] is up to 1e6, diff can be up to MOD, product may be up to 1e15, Python int fine.
Now we must handle the case k=0? But constraints: 1 ≤ k ≤ n, so k>=1.
Edge Cases: When k=1, then C(cnt,1) = cnt. So comb[m] = m if m>=1 else 0. Then diff = (new) - (old) = 1 always. So total_sum update = sum_{d|x} phi[d] * 1. But sum_{d|x} phi(d) = x. Indeed classical identity. So total_sum would increase by x each time we add a number? Let's see: For k=1, answer sum over subsets of size 1 of gcd(single element) = sum of all elements. So total_sum should be sum of all numbers. That matches because each addition adds x to sum. Our update would be sum_{d|x} phi[d] * 1 = x. So works.
Now we need to confirm that for k>1, this formula works.
Now complexity: Precomputations: Sieve up to 1e6 for phi and SPF. That's O(maxVal log log maxVal) ~ 1e6, fine.
Divisor enumeration: For each x, we need to generate all divisors. We'll factor x via SPF: while x>1: get p, count exponent, etc. We'll build factorization list. Then generate divisors: typically recursion or iterative.
Implementation details in Python:
- Use list for spf of size maxVal+1.
- Compute spf using standard sieve:
spf = list(range(maxVal+1))
for i in range(2, int(maxVal**0.5)+1):
if spf[i] == i:
for j in range(i*i, maxVal+1, i):
if spf[j] == j:
spf[j] = i
- Compute phi using Euler's totient via spf? Actually we can compute phi via sieve as well: initialize phi[i]=i, then for each prime p, for multiples, phi[m] -= phi[m]//p. But we need efficient. Since we have spf, we could compute phi for each number using factorization, but that would be O(N log log N) to compute phi for all numbers via sieve.
Better: compute phi array separately using linear sieve or the classic Euler's totient sieve:
phi = list(range(maxVal+1))
for i in range(2, maxVal+1):
if spf[i] == i: # prime
for j in range(i, maxVal+1, i):
phi[j] -= phi[j] // i
But careful: That works if we iterate i from 2 to maxVal and only for primes? Actually the classic method: for each i from 2 to N, if i is prime, then for multiples... But we can get primes from spf: if spf[i]==i. That yields primes. Then for each prime p, for multiples m of p, phi[m] -= phi[m] // p. This works because phi[m] is initially m. However note: we must ensure that for each prime we only subtract once? Actually phi[m] = m * ∏_{p|m} (1-1/p). The algorithm: for each prime p, for each multiple m of p, do phi[m] -= phi[m] // p. This works because starting from m, we subtract the fraction due to each prime factor. However, this will work correctly regardless of order? Yes, standard.
Alternatively compute phi using linear sieve in same loop as spf. But above is fine.
Now, precompute comb array:
MOD = 10**9+7
fact = [1]*(N_total+1)
for i in range(1, N_total+1): fact[i] = fact[i-1]i % MOD
inv_fact = [1](N_total+1)
inv_fact[N_total] = pow(fact[N_total], MOD-2, MOD)
for i in range(N_total, 0, -1): inv_fact[i-1] = inv_fact[i]i % MOD
comb = [0](N_total+1)
if k == 0:
comb[0] = 1
else:
for m in range(k, N_total+1):
comb[m] = fact[m] * inv_fact[k] % MOD * inv_fact[m-k] % MOD
For m < k, comb[m] = 0 (already)
Note: For m < k, comb remains 0.
Now, cnt array: We need size maxVal+1, but maxVal could be up to 1e6. Use list of integers of length maxVal+1.
Now, function to get divisors of x:
def get_divisors(x):
# factorize using spf
factors = []
while x > 1:
p = spf[x]
exp = 0
while x % p == 0:
x //= p
exp += 1
factors.append((p, exp))
# generate divisors
divs = [1]
for p, exp in factors:
current_len = len(divs)
multiplier = 1
for e in range(1, exp+1):
multiplier *= p
for i in range(current_len):
divs.append(divs[i] * multiplier)
return divs
But careful: After factorizing, x becomes 1. We must not modify original x, so use a copy: tmp = x. Use tmp.
However, we might call get_divisors many times (200k). This function does loops and creates new list each time. That's fine.
Potential optimization: For numbers that appear multiple times, we could cache divisors list, but not necessary.
Now, main loop: For each number val in initial list + queries, we call add(val). For add, we get divisors, then for each d:
old = cnt[d]
new = old + 1
total_sum = (total_sum + phi[d] * (comb[new] - comb[old])) % MOD
cnt[d] = new
But note: comb[old] might be 0 if old < k, similarly comb[new] might be 0 if new < k. That's fine.
We need to ensure we take modulo after diff: diff = comb[new] - comb[old]; total_sum = (total_sum + phi[d] * diff) % MOD. Since diff may be negative, we can compute as (total_sum + phi[d]*diff) % MOD, Python's % yields non-negative if we do (total_sum + phi[d]*diff) % MOD, but careful: (total_sum + negative) % MOD yields correct non-negative remainder. However, to avoid large intermediate, we can compute total_sum = (total_sum + phi[d] * (comb[new] - comb[old])) % MOD. That's okay.
But note: phi[d] up to 1e6, comb values up to MOD-1, diff up to MOD-1, product up to 1e12, fits in Python int.
Now we need to handle initial sum: after processing initial n numbers, we have total_sum ready. Then for each query, we add and print.
Now check example:
n=3,k=3,q=2. a=[4,6,9]; c=[8,6].
We can simulate:
Precompute phi up to max=9? Actually max will be 9? But later 8 and 6, max=9. phi: 1->1,2->1,3->2,4->2,6->2,8->4,9->6? Wait compute phi: φ(1)=1, φ(2)=1, φ(3)=2, φ(4)=2, φ(6)=2, φ(8)=4, φ(9)=6. Actually φ(9)=6 because numbers 1..9 coprime to 9: 1,2,4,5,7,8 ->6.
Now total numbers N_total=5.
Precompute comb for k=3: C(m,3): C(3,3)=1, C(4,3)=4, C(5,3)=10.
Now initial: cnt all zero.
Add 4: divisors of 4: 1,2,4. For each:
d=1: old=0,new=1; comb[1]=0, comb[0]=0 diff=0; total_sum unchanged. cnt[1]=1.
d=2: old=0,new=1 diff=0.
d=4: old=0,new=1 diff=0.
After adding 4, total_sum=0.
Add 6: divisors of 6:1,2,3,6.
d=1: old=1,new=2; comb[2]=0 (since 2<3), comb[1]=0 diff=0.
d=2: old=1,new=2 diff=0.
d=3: old=0,new=1 diff=0.
d=6: old=0,new=1 diff=0.
total_sum still 0.
Add 9: divisors:1,3,9.
d=1: old=2,new=3; comb[3]=1, comb[2]=0 diff=1. phi[1]=1 => total_sum +=1 -> total_sum=1.
d=3: old=1,new=2; comb[2]=0, comb[1]=0 diff=0.
d=9: old=0,new=1 diff=0.
Now total_sum=1. But expected initial sum after three species? Actually we haven't output anything yet. The problem says after first day we have species 4,6,9,8 (since day1 adds 8). So initial set before any day is (4,6,9). They computed sum over subsets of size 3 (only one subset) = gcd(4,6,9)=1. So total_sum=1. That matches.
Now add day1: c=8. Divisors of 8:1,2,4,8.
Update:
d=1: old=3,new=4; comb[4]=4, comb[3]=1 diff=3; phi1=1 => total_sum+=3 => total_sum=4.
d=2: old=2,new=3; comb[3]=1, comb[2]=0 diff=1; phi2=1 => total_sum+=1 => 5.
d=4: old=1,new=2; comb[2]=0, comb[1]=0 diff=0 => no change.
d=8: old=0,new=1; comb[1]=0, comb[0]=0 diff=0.
Now total_sum=5. That matches output 5.
Now add day2: c=6. Divisors of 6:1,2,3,6.
d=1: old=4,new=5; comb[5]=10, comb[4]=4 diff=6; phi1=1 => total_sum=5+6=11.
d=2: old=3,new=4; comb[4]=4, comb[3]=1 diff=3; phi2=1 => total_sum=14.
d=3: old=2,new=3; comb[3]=1, comb[2]=0 diff=1; phi3=2 => total_sum=14+2=16.
d=6: old=1,new=2; comb[2]=0, comb[1]=0 diff=0; phi6=2 => 0.
total_sum=16. Matches.
So formula works.
Now second example: n=4,k=1,q=2. a=[6,5,4,3]; c=[2,1]. Total numbers=6.
Precompute comb for k=1: comb[m]=m for m>=1 else 0. phi: any.
Initial: process 6,5,4,3:
Add 6: divisors of 6:1,2,3,6; each update diff=1 (since comb increases by 1). So total_sum increment = sum_{d|6} phi(d) = 6. total_sum=6.
Add 5: divisors:1,5; sum phi=5 => total_sum=11.
Add 4: divisors:1,2,4; sum phi=4 => total_sum=15.
Add 3: divisors:1,3; sum phi=3 => total_sum=18? Wait expected after initial (4 species) sum over subsets of size 1 is sum of all numbers = 6+5+4+3=18. Yes 18. But sample says after first query output 20? Actually sample: output after first day is 20, after second day 21. Let's see: They have n=4, initial species counts: 6,5,4,3. After first day, receive c=2, so total species: 6,5,4,3,2 sum = 20. So after initial (before any day) they didn't output. After first day they output 20. So after processing initial 4, total_sum=18. Then add c=2: sum phi(divisors of 2)=2, total_sum becomes 20. Then add c=1: sum phi(divisors of 1)=1, total_sum=21. Matches.
Thus algorithm correct.
Now we need to ensure we compute phi(d) correctly for d up to max value 1e6. Also note that d values may be up to max a_i or c_j; but when we get divisors, d might be up to the number itself, which is within maxVal.
Now complexity: total insertions N_total <= 200k. For each insertion, divisor enumeration (average maybe 100). So total operations ~ 20 million plus some overhead for factorization. 20 million loops in Python might be okay if optimized and using PyPy. However we also have to generate divisors, which involves building list and recursion. The loop inside add (for each divisor) is simple. Factorization while loops: each number reduces by dividing primes, complexity O(number of prime factors). So overall maybe 30-40 million operations. Should be okay under PyPy if we code efficiently.
But we also need to be careful about modulo for total_sum: we mod after each update? Could accumulate and mod at end, but it's fine.
Now consider memory: cnt array size maxV+1 = 1,000,001 ints. In Python, list of ints each 28 bytes? That would be 28 MB; but using array('I') from array module or maybe using list of ints is okay? 1e6 ints ~ 8 MB if using array('I') or using list of ints? Actually Python int is an object, each ~28 bytes, so 1e6 ints would be 28 MB, plus list overhead maybe 8 MB, total ~36 MB, still okay for typical limit (256 MB). But we also have phi array (list of ints) same size, plus spf array (int), plus comb (200k ints), etc. So total memory maybe ~100 MB, which is acceptable. However using list of ints for large arrays may be heavy but still under 256 MB. We can use array module to reduce memory, but not necessary.
But we can also use Python's built-in list for these arrays; they are fine.
However, for cnt array, we need to increment many times, but using Python int objects may be slower due to boxing/unboxing. But still okay.
Alternatively, we could use a dictionary for cnt to store only divisors that appear, because many d may never appear. But given numbers up to 1e6 and many insertions, many divisors will be hit. However number of distinct d that appear could be up to maybe ~maxV? Since many numbers generate many divisors, but the union of all divisors from 200k numbers each up to 1e6 could be large but likely less than 1e6? Actually any d that divides at least one of the numbers will appear. Could be up to maxV if we have numbers covering all values. But with 200k numbers up to 1e6, they could cover many but not all; still could be up to 200k distinct divisors? Actually each number's divisors are ≤ itself; the set of all numbers might not include all integers up to 1e6. But worst-case, if we have numbers 1,2,...,1e6, then all d appear. But we have only 200k numbers, so at most 200k distinct numbers? But divisors of those numbers could be many. For instance, if we have all numbers from 1 to 200k, their divisors include many small numbers, probably covering all numbers up to 200k and some beyond. In worst-case, could be near 1e6? But unlikely. But to be safe, we can allocate full array of size maxV+1. That's 1e6+1 entries; memory okay.
But we must ensure that we don't allocate too many large lists if maxV is 1e6; that's fine.
Now we need to compute phi for all up to maxV. We can compute using linear sieve that also yields primes and phi. Let's implement:
def compute_totient_and_spf(N):
phi = list(range(N+1))
spf = list(range(N+1))
primes = []
for i in range(2, N+1):
if spf[i] == i:
primes.append(i)
for p in primes:
if p > spf[i] or i * p > N:
break
spf[i * p] = p
# phi update: if p divides i, phi[ip] = phi[i] * p
# else phi[ip] = phi[i] * (p-1)
# But easier: after building spf, compute phi separately as described.
# But we need phi anyway. Could compute in same loop.
But it's easier to compute spf via classic sieve, and then compute phi separately using the prime iteration method: for p in primes: for j in range(p, N+1, p): phi[j] -= phi[j] // p.
But we need primes list. So we can first do sieve to get primes and spf.
Simpler: Use standard linear sieve to compute both spf and phi in O(N). That's efficient and avoids extra loops. Let's do:
N = maxV
spf = [0](N+1)
phi = [0](N+1)
primes = []
phi[0] = 0
phi[1] = 1
for i in range(2, N+1):
if spf[i] == 0: # prime
spf[i] = i
primes.append(i)
phi[i] = i-1
for p in primes:
if p > spf[i] or i * p > N:
break
spf[i * p] = p
if i % p == 0:
phi[i * p] = phi[i] * p
break
else:
phi[i * p] = phi[i] * (p-1)
For i=1, set phi[1]=1 earlier.
But careful: we need to initialize spf for 1? Usually spf[1] = 1. But we can set spf[0]=0, spf[1]=1. The loop from 2. Then after loop, set phi[1]=1.
Alternatively, we can use a standard Euler's totient sieve that computes phi via product formula using spf. However linear sieve is fine.
But note: For phi, we need phi[d] for all d, including 1. So we'll set phi[1]=1.
Now spf array will be used for factorization: for any x>1, we repeatedly divide by spf[x] to get factors.
Now, we must be careful about maxV: we need to compute up to maximum value among a_i and c_j. So we can read all inputs first? But we need to output after each query. However we can pre-read all numbers to know maxVal. That's allowed: we can read entire input, store initial a list and c list, compute maxVal = max(max(a_i), max(c_j)). Then precompute up to that maxVal.
But careful: The input may be large, but we can read all.
Edge Cases: When k > total numbers? But constraints: k ≤ n initially, but after adding, total numbers n+q ≥ n ≥ k, so okay.
Now we need to handle modulo: Use MOD = 10**9+7.
Now ensure that comb array is computed for all m up to n+q. But we also need comb values for cnt values up to total numbers. Since cnt[d] increases as we add numbers, but cnt[d] cannot exceed total numbers N_total. So we compute comb up to N_total.
Implementation steps:
- Read input lines. Use sys.stdin.buffer.read() to read all ints quickly.
- Parse ints.
- n, k, q = first three.
- Then read n values for a_i.
- Then read q values for c_j.
- Determine maxVal = max(max(a_i), max(c_j), 1) (at least 1).
- Determine N_total = n+q.
- Precompute spf and phi up to maxVal.
- Precompute comb array up to N_total.
- Initialize cnt = [0]*(maxVal+1)
- total_sum = 0
- Define function add_number(x):
get divisors list.
for d in divisors:
old = cnt[d]
new = old + 1
diff = comb[new] - comb[old]
total_sum = (total_sum + phi[d] * diff) % MOD
cnt[d] = new
But we need total_sum to be nonlocal variable. In code, we can just update a global variable.
- Process each a_i: add_number(a_i)
- Then for each c_j: add_number(c_j); after each addition, append total_sum to output list.
- Print each output line.
Now we need to implement divisor generation efficiently.
Divisor generation using prime factorization:
def get_divisors(x):
# returns list of divisors
# use tmp = x
divisors = [1]
while x > 1:
p = spf[x]
exp = 0
while x % p == 0:
x //= p
exp += 1
# multiply current divisors by p^e for e=1..exp
current_len = len(divisors)
mul = 1
for _ in range(exp):
mul *= p
for i in range(current_len):
divisors.append(divisors[i] * mul)
return divisors
This is efficient.
Potential optimization: Since we call this many times, the repeated list creation and loops may be costly. But it's okay.
Now, we also need to note that phi[d] may be 0 for d=0? But d starts from 1.
Now, we need to think about cases where k > N_total? Not possible.
Now we should test with sample.
Edge Cases: k=0? Not possible.
Now we must consider that for large k, comb array may have many zeros for small m. That's fine.
Now we should confirm that the formula holds for subsets of size k where some subsets may have the same species? But species are distinct. So each species is unique. So selecting subset of species, each species appears at most once. That's correct: we select k distinct species. So our combination counts subsets of species, not multiset. The formula using C(cnt_d, k) counts number of subsets of size k where all chosen species counts are multiples of d. Since species are distinct, that's correct.
Now we have to ensure that phi(d) for d up to maxVal is computed correctly. Note that we need phi for d possibly up to 1e6, but numbers may be up to 1e6. So precomputation is okay.
Now let's estimate total divisor enumeration count: For each insertion, number of divisors average for numbers up to 1e6. The average divisor count for numbers up to N is about log N. Actually average number of divisors for numbers up to 1e6 is around maybe 100? Let's check: The average d(n) for n up to 1e6 is about log n + (2γ -1) ~ ln(1e6)+0.154 = about 13.8+0.154=14? Actually average divisor count is about log n? Wait, the average order of d(n) is log n. For n=1e6, log(1e6) ≈ 13.8. But I've seen data: average divisor count up to 1e6 is around 100? That seems off. Actually d(n) on average is about log n + (2γ -1) ~ log n + 0.154. For n=10^6, natural log ~13.8, so average ~14. So typical number of divisors is around 100 only for highly composite numbers. So average is small, maybe around 100? No, 14 is average. But many numbers have many small divisors, but still average is low. However, the worst-case is 240, but average maybe ~ 100? Let's approximate: For random number up to 1e6, average divisor count is about 100? I'd check: Actually the average of d(n) for n ≤ x is (1/x) * ∑_{n≤x} d(n) = log x + (2γ -1) + O(1/√x). For x=10^6, log(10^6) ≈ 13.8155, 2γ -1 ≈ 2*0.57721 -1 = 0.15442, so ~13.97. So average about 14. So total divisor visits across 200k numbers is about 2.8 million, which is very small! Wait, that's surprising but indeed average divisor count is small. I recall that divisor function grows slowly. So 200k * 14 = 2.8 million. That's very manageable. Even if average is 100, it would be 20 million, still okay. But from theory, average is about log n, so it's small. So our algorithm is efficient.
But we need to confirm: The average number of divisors for numbers up to 1e6 is indeed about 14-15. So total divisor enumeration is only a few million, which is trivial.
Thus the algorithm will be fast.
Now we must be careful about factorizing each number: factorization using spf also takes O(number of prime factors) which is at most log n, so negligible.
Therefore overall algorithm is fine.
Now we should implement.
Implementation details:
-
Use sys.stdin.buffer.read() to read all ints as bytes and split.
-
Parse ints: data = list(map(int, sys.stdin.buffer.read().split())).
-
Then n = data[0]; k = data[1]; q = data[2]; then a = data[3:3+n]; then c = data[3+n:3+n+q].
-
Determine maxVal = max(max(a), max(c), 1).
-
N_total = n + q.
-
Precompute spf and phi up to maxVal.
Implement linear sieve:
def linear_sieve(limit):
spf = [0](limit+1)
phi = [0](limit+1)
primes = []
phi[0] = 0
phi[1] = 1
for i in range(2, limit+1):
if spf[i] == 0:
spf[i] = i
primes.append(i)
phi[i] = i-1
for p in primes:
if p > spf[i] or ip > limit:
break
spf[ip] = p
if i % p == 0:
phi[ip] = phi[i] * p
break
else:
phi[ip] = phi[i] * (p-1)
return spf, phi
But note: For i=1, we set phi[1]=1 manually after? In loop from 2, we need to set phi[1] explicitly. So after function, set phi[1]=1. Also spf[1] could be set to 1 if needed, but for factorization we only call on x>1. But we may need spf[1]? Not needed.
Alternatively we can initialize spf as list of 0s and phi as 0s, then after loop set phi[1]=1.
Check: In loop for i=2... we fill phi for composites. Works.
Testing small:
limit=10:
i=2 prime, phi[2]=1.
i=3 prime, phi[3]=2.
i=4: spf[4] initially 0? But we will compute: spf[4]==0? Actually after previous steps, spf[4] still 0, but 4 is composite, not prime, so spf[4] remains 0? In linear sieve, we fill spf for composites as we go. For i=4, we check if spf[4]==0? This condition is for primes; for composites, spf[4] should have been set when ip generated it? Actually when i=2, we iterate primes: p=2, 22=4 <= limit, set spf[4]=2, then break because i%p==0. So before reaching i=4, spf[4] is already set to 2. So when i=4, spf[4] !=0, so we treat it as composite and skip prime addition. So that's fine.
Thus linear sieve works.
Now, after we have spf and phi, we can compute comb.
But note: For comb[new] and comb[old], we need values up to N_total. Since we precompute comb up to N_total, we must ensure that during insertion, new <= N_total. Since we add numbers one by one, cnt[d] increases but never exceeds total numbers inserted so far, which is at most N_total. So it's safe.
Now, we need to be careful about when new > N_total? It can't happen because we only add numbers up to N_total.
Now, we might also need to handle modulo negative diff: using (comb[new] - comb[old]) % MOD but we multiply by phi[d] and then add to total_sum. Better to compute diff = comb[new] - comb[old]; then total_sum = (total_sum + phi[d] * diff) % MOD. Since Python's modulo yields non-negative for total_sum, but diff may be negative, so the product may be negative. However when we do % MOD after addition, we get correct modulo. But to avoid large negative intermediate, we can compute as total_sum = (total_sum + phi[d] * (comb[new] - comb[old])) % MOD. That's fine.
Now, we should define phi as list of ints, but phi[d] may be up to 1e6, diff may be up to MOD-1, product up to 1e12, Python handles.
Now, we should also note that for large N_total (200k), computing factorial for comb using factorials is fine.
Now, we need to output after each query. We'll collect results in list and print with '\n'.join(map(str, results)).
Now test with samples.
Now let's think about potential overflow in phi computation: Not an issue.
Now, we need to ensure that we use correct data types.
Edge Cases: If k > N_total? But not.
Now, what about modulo for comb values? comb array stores modulo MOD values. So diff is modulo difference. The formula sum_{d} φ(d) * C(cnt_d, k) mod MOD works because we are summing mod MOD and φ(d) is integer, but note that φ(d) is not taken modulo? It can be taken modulo MOD as well because we multiply and mod. So it's fine.
Now, let's double-check the derivation: Sum_{S} gcd(S) = ∑_{d} φ(d) * C(cnt_d, k). This is an identity over integers. When we compute modulo MOD, we compute each term modulo MOD. Since all operations are integer addition/multiplication, we can take modulo at each step.
Now, we must verify that we didn't miss any condition: The subsets are of distinct species. Our cnt_d counts number of species whose flower count is divisible by d. Since each species is unique, number of subsets of size k all divisible by d is C(cnt_d, k). So correct.
Now, we should also consider that the species are distinct, but the counts may be the same. That doesn't matter.
Now, we have to handle the case when k=0? Not needed.
Now, we should test with another small case manually.
Case: n=2, k=2, a=[4,6]. Then only subset is {4,6}, gcd=2. Our formula: cnt_d: numbers divisible by 1:2 -> C(2,2)=1 * φ(1)=1 ->1; numbers divisible by 2: both (4,6) divisible by 2? 4%2=0,6%2=0 -> cnt_2=2 -> C(2,2)=1 * φ(2)=1 ->1; numbers divisible by 3: only 6? cnt_3=1 -> C(1,2)=0; numbers divisible by 4: only 4? cnt_4=1 ->0; numbers divisible by 6: only 6? cnt_6=1 ->0; sum =1+1=2. Correct.
Now, case: n=3,k=2,a=[4,6,9]. Subsets: {4,6}:gcd=2; {4,9}:1; {6,9}:3; sum=2+1+3=6. Our formula: compute cnt_d:
- d=1: all three divisible -> cnt=3 -> C(3,2)=3, φ(1)=1 =>3
- d=2: numbers divisible by 2: 4,6 -> cnt=2 -> C(2,2)=1, φ(2)=1 =>1
- d=3: numbers divisible by 3: 6,9 -> cnt=2 -> C=1, φ(3)=2 =>2
- d=4: only 4 -> cnt=1 -> 0
- d=6: only 6? Actually 6 divisible by 6 -> cnt=1 ->0
- d=9: only 9 ->0
- d=?? others zero.
Sum = 3+1+2 =6. Good.
Thus formula is correct.
Now, we can proceed to coding.
Potential performance concerns:
-
Generating divisors for each number via factorization and building list can be optimized by avoiding list creation? But needed.
-
Using Python recursion for divisor generation might be slower; iterative method above is fine.
-
We may want to pre-allocate an array for divisors? Not necessary.
-
Use local variables in loops to avoid global lookups.
-
Use for d in divisors: inside that loop, use local references: cnt_local = cnt, phi_local = phi, comb_local = comb, total_sum as integer (but updated). However we need to update cnt array; we can use list assignment.
We'll define add_number as a function that updates global total_sum, but we can inline code for speed? Since we call it many times (200k), it's fine to have a function but careful about variable lookups. We can define inside main and use nonlocal if needed. But maybe we can just write loop for each number.
Given that we have many numbers, we might want to avoid function call overhead. But 200k function calls is okay. However, we also have to call get_divisors function per number, which is another call. Could inline but okay.
We'll write:
def get_divisors(x):
...
total_sum = 0
for val in a:
divs = get_divisors(val)
for d in divs:
old = cnt[d]
new = old + 1
total_sum += phi[d] * (comb[new] - comb[old])
# mod later?
cnt[d] = new
after loop, mod total_sum
But total_sum may become large; we can take modulo periodically or after each addition? Since total_sum could become large (max around 1e12 * 1e5? Actually sum up to 1e6 * 1e5 = 1e11, times maybe 1e5? Actually total_sum final value could be up to sum over subsets gcd; worst-case each gcd can be up to 1e6, number of subsets C(200k, k) huge, but we take modulo. So total_sum must be reduced modulo MOD to avoid huge ints (though Python big ints can handle but may be slow). So better to mod after each update, or after each inner loop? But we can do total_sum %= MOD after each number's processing, or after each divisor update.
Since we do total_sum = (total_sum + phi[d] * (comb[new] - comb[old])) % MOD each time, that's okay but modulo operation is somewhat expensive. We could accumulate delta and mod after processing all divisors for a number. But that would increase intermediate size; but per number delta maybe up to 1e6 * 200 (since up to 200 divisors) = 2e8, not huge. But we could also accumulate total_sum without mod and mod after each number or after each query to reduce modulo operations. But total_sum could accumulate over many numbers to large values: after 200k numbers, each addition can add up to maybe 1e9 * 200 = 2e11, times 200k = 4e16, still within Python's big int capacity (maybe 64-bit? Actually Python ints arbitrary precision, but arithmetic becomes slower with huge numbers. But 4e16 fits in 65 bits, still fast. Actually 4e16 is 4*10^16, which is about 2^55, fits in 64-bit. So maybe we can avoid modulo until the end? But we need output after each query, so we need total_sum mod MOD. However we could keep total_sum as Python integer and mod when output. But intermediate values may become larger: after 200k insertions, each insertion adds at most sum_{d|x} phi(d) * (comb[new]-comb[old]). But comb differences can be large: when cnt_d is near N_total, comb values can be huge (C(200k, k) mod MOD, but we store them modulo MOD. So diff is modulo MOD, but it's not actual integer difference; it's the modular representation of the difference. Actually comb[new] and comb[old] are computed mod MOD. Their difference (comb[new] - comb[old]) may be negative mod MOD, but we treat it as integer difference modulo MOD? Wait careful: Our formula sum_{d} φ(d) * C(cnt_d, k) mod MOD. Since we store C(cnt, k) modulo MOD, we can compute the sum modulo MOD using these modded values. However, is it valid to use C(cnt, k) mod MOD in the difference and then multiply by φ(d)? Yes, because we want the result modulo MOD, and the expression is linear combination modulo MOD. So we can compute comb as C(cnt, k) % MOD. Then diff = (comb[new] - comb[old]) % MOD. But earlier we used integer diff without modulo and then multiplied and added to total_sum then modded. That is equivalent to using diff modulo MOD, because total_sum is maintained modulo MOD. However if we do not mod total_sum after each step, we need to ensure that we use actual integer values of C(cnt, k) not modulo MOD? Actually the sum modulo MOD is (Σ φ(d)*C(cnt_d,k)) mod MOD. If we store C(cnt_d,k) mod MOD, then the product φ(d) * (C_mod) mod MOD is correct. But if we use diff = C_mod[new] - C_mod[old] (which is an integer possibly negative but representing difference modulo MOD), and then add to total_sum (which we keep modulo MOD) and then mod, it's fine because we are essentially doing arithmetic modulo MOD. But if we skip modding total_sum, total_sum becomes sum of terms each of which is φ(d)*C_mod (where C_mod is in range [0,MOD-1]), but that's not the actual integer C(cnt,k) but its residue. The sum of residues times φ(d) is not equal to the actual integer sum mod MOD? Actually it is: (Σ φ(d)*C(cnt,k)) mod MOD = Σ (φ(d) * (C(cnt,k) mod MOD)) mod MOD? Because modulo distributes: (a * b) mod M = ((a mod M) * (b mod M)) mod M. And sum mod M = (Σ (a_i mod M)) mod M, but careful: if we replace each C(cnt,k) by its residue modulo MOD, then sum of products φ(d)*residue modulo MOD equals the sum of φ(d)*C(cnt,k) modulo MOD because φ(d) is integer and we can take modulo on each term: (φ(d)(C mod M) mod M. But φ(d) may be larger than MOD? MOD is 1e9+7, φ(d) <= 1e6, so φ(d) mod M = φ(d). So using C_mod is fine. So we can treat C(cnt,k) as its residue. Then diff = (C_mod[new] - C_mod[old]) (which is integer difference of residues). That difference may not equal (C(cnt_new,k) - C(cnt_old,k)) mod MOD? Actually (C_new_mod - C_old_mod) mod MOD is equal to (C_new - C_old) mod MOD because subtraction respects mod. So it's fine. So we can maintain total_sum as integer modulo MOD.
Thus we can mod total_sum after each addition to keep it small. Or we can accumulate as Python int and mod when output. Since values are small, we can mod after each update to keep it within MOD range. Mod operation is cheap.
Now, we need to be careful about negative diff: when diff negative, product might be negative. Doing total_sum = (total_sum + phi[d] * diff) % MOD will yield correct mod. But if we want to avoid negative, we could compute diff_mod = (comb[new] - comb[old]) % MOD, then total_sum = (total_sum + phi[d] * diff_mod) % MOD. That's extra % per diff but might be slower. We can do as before and rely on Python's % handling negative.
Now, about comb array: we compute it modulo MOD. For m < k, comb[m]=0. For m >= k, comb[m] = C(m,k) % MOD. So diff = comb[new] - comb[old] may be negative; but that's okay.
Now, we should precompute comb array up to N_total. However note: When we compute comb for m up to N_total, we need fact and inv_fact only if we compute using formula. That's fine.
But there is nuance: The binomial coefficient C(m,k) for m up to 200k and k up to 100k can be computed using factorial precomputation. That's standard.
Now we need to ensure that we compute factorial up to N_total correctly, including inv_fact.
Implementation of factorial precomputation:
fact = [1] * (N_total+1)
for i in range(1, N_total+1):
fact[i] = fact[i-1] * i % MOD
inv_fact = [1] * (N_total+1)
inv_fact[N_total] = pow(fact[N_total], MOD-2, MOD)
for i in range(N_total, 0, -1):
inv_fact[i-1] = inv_fact[i] * i % MOD
comb = [0] * (N_total+1)
if k <= N_total:
for m in range(k, N_total+1):
comb[m] = fact[m] * inv_fact[k] % MOD * inv_fact[m-k] % MOD
Now, there is a possibility that k is large (e.g., k=100k, N_total=200k). The loop from k to N_total is about 100k, which is fine.
Now, we also need to consider that cnt[d] may exceed N_total? No.
Now, we need to ensure that we handle large input and output efficiently. Use sys.stdout.write.
Now, one more optimization: Since we only need to update cnt[d] for divisors of x, and we only need to know old count, we can just increment. However, we also need to compute phi[d]. That's precomputed.
Now, we need to be careful about the case where d > maxVal? But divisors are ≤ x ≤ maxVal, so fine.
Now, we also need to note that we may have numbers with value 1. Its divisors: [1]. That works.
Now, we test with sample.
Now, we might worry about time for generating divisors using while loops and list appends. But it's fine.
Now, we implement.
But before finalize, we need to consider if we can handle up to 1e6 numbers with linear sieve efficiently: linear sieve O(N). For N=1e6, it's fine.
Now, let's consider memory for cnt: we allocate list of length maxVal+1. That's 1,000,001 integers. In Python, each integer is an object, overhead high. Could cause memory about 28 MB for cnt, plus phi same, spf same, that's 328=84 MB, plus other arrays maybe 100 MB, still okay but close to typical 256 MB limit. However, Python ints are 28 bytes each for small ints (less than 2^30). So 1e6 ints = 28 MB. Three such arrays = 84 MB. Plus other arrays like comb (200k ints) ~5.6 MB, fact/inv_fact ~400k ints? Actually fact and inv_fact each N_total+1 (200k) -> each ~5.6 MB, both ~11.2 MB. So total ~ 84+11 = 95 MB, plus spf (same size) -> wait we already counted spf? Actually we have spf array also size maxVal+1, that's another 28 MB, so total: cnt (28), phi (28), spf (28) = 84 MB. plus fact, inv_fact, comb ~ 3 * 200k * 28 = 35.6=16.8 MB. So total ~100 MB. plus other overhead, still within 256 MB. So okay.
But if we are concerned, we could use array('I') from array module to store integers as 32-bit unsigned, which reduces memory drastically (4 bytes per element). But then operations become a bit slower due to conversion? But maybe not needed. However, for cnt we need to store up to 200k, which fits in 32-bit. phi up to 1e6 also fits in 32-bit. spf up to 1e6 fits in 32-bit. So we can use array('I') to reduce memory. But we also need to index these arrays, and Python's array indexing returns Python int but still fine. Might be slightly slower due to conversion? But memory is more important if we have many arrays. 100 MB is fine.
But some judges have memory limit 256 MB, so it's safe.
Nevertheless, we can consider using lists of ints; it's simpler.
Now, edge case: If maxVal is 0? Not possible because ai >=1.
Now, let's consider the case when k > current number of species? Actually after each addition, the number of species is n + j. Since k ≤ n initially, and we only add new species, after each addition, the number of species is >= n ≥ k, so it's fine. But our comb array is defined for all m up to N_total, and we only use comb[new] when new <= N_total. When we start adding numbers, cnt[d] increases gradually, but it will never exceed total numbers inserted so far. However, we might use comb[new] when new > current total inserted? Actually new = old+1, old is current count of species that are multiples of d. Since we have inserted that many numbers so far (including the current one). That count cannot exceed the total number inserted so far, which at most N_total. So it's safe.
Now, we need to ensure that comb is computed for all m from 0 to N_total, inclusive. That's done.
Now, one more nuance: The initial numbers are added before any query, but we might also need to output something before any query? No, output only after each day (i.e., after each new species added). So we don't output after initial insertion.
Now, let's think about multiple test cases? Input only one case.
Now, implement.
We'll write code:
import sys
MOD = 10**9+7
def main():
data = list(map(int, sys.stdin.buffer.read().split()))
it = iter(data)
n = next(it); k = next(it); q = next(it)
a = [next(it) for _ in range(n)]
c = [next(it) for _ in range(q)]
maxVal = max(max(a) if a else 0, max(c) if c else 0, 1)
N_total = n + q
# Precompute spf and phi up to maxVal
spf = [0]*(maxVal+1)
phi = [0]*(maxVal+1)
primes = []
phi[0] = 0
phi[1] = 1
for i in range(2, maxVal+1):
if spf[i] == 0:
spf[i] = i
primes.append(i)
phi[i] = i-1
for p in primes:
if p > spf[i] or i*p > maxVal:
break
spf[i*p] = p
if i % p == 0:
phi[i*p] = phi[i] * p
break
else:
phi[i*p] = phi[i] * (p-1)
# phi[1] already set
# Precompute comb C(m, k) for m=0..N_total
fact = [1]*(N_total+1)
for i in range(1, N_total+1):
fact[i] = fact[i-1] * i % MOD
inv_fact = [1]*(N_total+1)
inv_fact[N_total] = pow(fact[N_total], MOD-2, MOD)
for i in range(N_total, 0, -1):
inv_fact[i-1] = inv_fact[i] * i % MOD
comb = [0]*(N_total+1)
if k <= N_total:
# Precompute factor for speed: f = inv_fact[k] * inv_fact[0]? Actually we need inv_fact[k] * inv_fact[m-k]
inv_fact_k = inv_fact[k]
for m in range(k, N_total+1):
comb[m] = fact[m] * inv_fact_k % MOD * inv_fact[m-k] % MOD
# cnt array
cnt = [0]*(maxVal+1)
total = 0
# function to add a number
def add_number(x):
nonlocal total
# get divisors
divs = [1]
temp = x
while temp > 1:
p = spf[temp]
exp = 0
while temp % p == 0:
temp //= p
exp += 1
cur_len = len(divs)
mul = 1
for _ in range(exp):
mul *= p
for i in range(cur_len):
divs.append(divs[i] * mul)
# now update for each divisor
for d in divs:
old = cnt[d]
new = old + 1
diff = comb[new] - comb[old] # Python ints, could be negative
total = (total + phi[d] * diff) % MOD
cnt[d] = new
# process initial n numbers
for val in a:
add_number(val)
# process queries and collect answers
out = []
for val in c:
add_number(val)
out.append(str(total))
sys.stdout.write('\n'.join(out))
if name == "main":
main()
Now, test with sample.
I'll simulate quickly (we already did mental). Should output "5\n16" and "20\n21".
But note: In second sample, after initial add of 4 numbers total=18, then after first c=2, total becomes 20, after second c=1 total=21. So outputs as given.
Now, we need to consider potential issue: In add_number, we recompute divisors for each x. However, we used variable 'temp' which we modify, but we also used 'x' only for reading. That's fine. But note that we used 'temp' inside the while loops, it gets changed. That's okay.
Now, performance: For each x, we build a list divs. In worst-case number with many divisors (like 720720), divs length 240, and we do nested loops: for each prime factor, we multiply existing divisors. That's fine.
Now, we also need to ensure that we do not exceed recursion depth, but we don't use recursion.
Now, check for correctness: phi[1] = 1, as set.
Now, what about numbers that are 1? Divisors list will be [1] because while temp>1 loop is not entered. So divs remains [1]. Then update for d=1. That's correct.
Now, we also need to be careful about spf for 0 and 1. We set spf[0]=0, spf[1]=0? Actually we never access spf[1] because temp>1 condition prevents. So fine.
Now, one more nuance: In linear sieve, we set spf[i] = i for primes. For composite, we set spf[i*p] appropriately. However, we did not set spf[1] to 1. That's okay because we won't use it.
Now, what about phi[0]? Not used.
Now, we need to compute inv_fact_k only once to speed up comb computation. That's done.
Now, note: In comb array, for m < k, we leave as 0. So diff for old and new may be 0 for many.
Now, potential overflow in diff multiplication? Not in Python.
Now, maybe we can speed up by precomputing list of divisors for each possible number up to maxVal? That would be memory heavy and not needed.
Now, consider that total_sum may become negative after a step because diff is negative, but we mod it. Using total = (total + phi[d] * diff) % MOD ensures non-negative.
Now, we should test with some random small cases to verify.
Let's implement a small test in mind.
n=2, k=2, a=[4,6] -> answer initial sum? Not output, but we can compute after adding second initial number: after adding both, total=2. Then if we add a new number e.g., 8, we can compute manually. Let's test:
After initial 4 and 6: total=2 (gcd(4,6)=2). Add 8: now species 4,6,8. Subsets of size2: {4,6}=2,{4,8}=4,{6,8}=2, sum=8. According to formula: cnt_d after adding 8: cnt_1=3 -> C(3,2)=3 φ1=1 =>3; cnt_2: numbers divisible by 2: all three -> C(3,2)=3 φ2=1 =>3; cnt_4: 4,8 -> C(2,2)=1 φ4=2 =>2; cnt_8: just 8? Actually 8 divisible by 8 only 8 -> cnt=1 =>0; cnt_? sum=3+3+2=8. So correct.
Now our update: adding 8, divisors:1,2,4,8. For d=1: old cnt1=2->3 diff= C(3,2)-C(2,2)=3-1=2? Wait C(2,2)=1, C(3,2)=3 diff=2; phi1=1 -> total +2 => from 2 to 4? Actually initial total=2 (after 4 and6). Then add 8: d=1 gives +2 -> total=4; d=2: old cnt2=2? Actually after 4 and6, numbers divisible by 2: 4,6 (both divisible by2) so cnt2=2? Check: 4%2=0,6%2=0, so cnt2=2. Then new=3, C(3,2)=3, C(2,2)=1 diff=2, phi2=1 -> total=6; d=4: old cnt4=1 (4), new=2, C(2,2)=1, C(1,2)=0 diff=1, phi4=2 -> total=8; d=8: old=0, new=1 diff=0. So total becomes 8. Works.
Now, we must be careful that we compute comb for m=2 and m=3 correctly: C(2,2)=1, C(3,2)=3. So comb[2]=1, comb[3]=3.
Now, we should verify comb for m=0,1,2,3: for k=2, comb[0]=0, comb[1]=0, comb[2]=1, comb[3]=3. Good.
Now, we have to ensure that for m = old value, we use correct comb. For old=2, comb[2]=1; new=3, comb[3]=3.
Now, what about case where old < k? For example, adding a number that makes cnt_d become k for first time. Then old = k-1, comb[old]=0, comb[new]=C(k,k)=1. So diff=1. Works.
Now, everything seems fine.
Now, let's consider possible overflow in phi multiplication: phi[d] up to 1e6, diff up to MOD (1e9), product up to 1e15, fits in Python int.
Now, we should also consider that we might have many numbers, and cnt[d] may become large, but comb[new] and comb[old] are computed modulo MOD, so they are within 0..MOD-1. So diff within -(MOD-1)..(MOD-1). So product within about ±1e15. That's fine.
Now, we should also consider that for numbers where x is large, but maxVal is up to 1e6, the linear sieve works.
Now, check time: For maxVal=1e6, linear sieve loops ~1e6 times with inner loop over primes. Usually efficient.
Now, we need to test the code with sample inputs. We'll run mental.
First sample: n=3,k=3,q=2, a=[4,6,9], c=[8,6].
Our code: maxVal=9? Actually max among a and c is 9? Wait c includes 8 and 6, max is 9. So maxVal=9. Precompute spf and phi up to 9. spf: [0,0,2,3,2,5,2,7,2,3]? Actually compute properly: primes: 2,3,5,7. spf: spf[2]=2, spf[3]=3, spf[4]=2, spf[5]=5, spf[6]=2, spf[7]=7, spf[8]=2, spf[9]=3. phi: phi[1]=1; phi[2]=1; phi[3]=2; phi[4]=2; phi[5]=4? Actually phi[5]=4; but we don't need many. But for d=2, phi=1; d=4, phi=2; d=8? Up to 9, phi[8]=4? Wait we need phi up to 9: phi[8]=4, phi[9]=6. So computed. Good.
N_total = 5. comb: for k=3: comb[0..2]=0, comb[3]=1, comb[4]=4, comb[5]=10.
cnt array size 10 (indices 0..9). All zero initially.
Processing initial a:
- 4: divisors [1,2,4]. For each: old=0,new=1 diff=comb[1]-comb[0]=0. total stays 0. cnt[1]=1,cnt[2]=1,cnt[4]=1.
- 6: divisors of 6 = [1,2,3,6]. For d=1: old=1 new=2 diff=comb[2]-comb[1]=0-0=0 -> total unchanged; d=2: old=1 new=2 diff=0; d=3: old=0 new=1 diff=0; d=6: old=0 new=1 diff=0. cnt[1]=2,cnt[2]=2,cnt[3]=1,cnt[6]=1.
- 9: divisors [1,3,9]. d=1: old=2 new=3 diff=comb[3]-comb[2]=1-0=1; phi1=1 -> total=1; d=3: old=1 new=2 diff=0; d=9: old=0 new=1 diff=0. total=1.
Now process c: first 8: divisors [1,2,4,8]. d=1: old=3 new=4 diff=comb[4]-comb[3]=4-1=3; total=1+31=4; d=2: old=2 new=3 diff=comb[3]-comb[2]=1-0=1; total=4+11=5; d=4: old=1 new=2 diff=0; d=8: old=0 new=1 diff=0; total=5. output 5.
Second c=6: divisors [1,2,3,6]. d=1: old=4 new=5 diff=10-4=6; total=5+61=11; d=2: old=3 new=4 diff=4-1=3; total=11+31=14; d=3: old=2 new=3 diff=1-0=1; phi3=2 -> total=14+2=16; d=6: old=1 new=2 diff=0; total=16. output 16.
Matches.
Second sample: n=4,k=1,q=2, a=[6,5,4,3], c=[2,1]. maxVal=6? Actually max among a and c is 6. So maxVal=6. phi up to 6: phi[1]=1,2=1,3=2,4=2,5=4,6=2. N_total=6. comb for k=1: comb[0]=0, comb[1]=1, comb[2]=2, comb[3]=3, comb[4]=4, comb[5]=5, comb[6]=6.
cnt size 7.
Process a:
6: divisors [1,2,3,6]. d=1: old0 new1 diff=1-0=1, total=1; d=2: diff=1 -> total=2; d=3: diff=1 -> total=4? Actually phi[3]=2, so add 2 => total=4? Wait compute step by step:
total init 0.
- d=1: total=0+1*1=1
- d=2: total=1+1*1=2
- d=3: total=2+2*1=4
- d=6: total=4+21=6? Actually phi[6]=2, diff=1 -> add 2 => total=6. So after 6, total=6. But expected sum after first number? Actually we are building full set; final total after all four numbers should be 18. So continue.
5: divisors [1,5]. d=1: old1 new2 diff=2-1=1, total=6+11=7; d=5: old0 new1 diff=1, phi5=4 -> total=7+4=11.
4: divisors [1,2,4]. d=1: old2 new3 diff=3-2=1, total=11+1=12; d=2: old2? Wait after 6 and5, cnt[2] is from 6: we incremented cnt[2] when processing 6. So cnt[2] currently =1 (only 6 divisible by 2? Actually 6 is divisible by 2, yes; also 4 will be added later. At this point before adding 4, cnt[2] =1? Let's recount: after 6: cnt[2]=1. After 5: no change. So cnt[2]=1. Now adding 4: d=2: old=1 new=2 diff=2-1=1? Wait comb[2]=2? Actually comb[1]=1, comb[2]=2, diff=2-1=1. phi2=1 => total becomes 12+1=13? But we need to recalc: Actually after 5, total=11. Then add 4:
- d=1: old cnt1 after 5? cnt1 after 6 and5: cnt1 was incremented for each number: after 6: cnt1=1, after 5: cnt1=2. So old=2, new=3 diff= comb[3]-comb[2]=3-2=1; total =11+1=12.
- d=2: old cnt2=1 (from 6), new=2 diff= comb[2]-comb[1] =2-1=1; total =12+1*1=13.
- d=4: old=0 new=1 diff=1; phi4=2; total=13+2=15.
Thus after adding 4, total=15. But expected after three numbers (6,5,4) sum is 6+5+4=15. Good.
Now add 3: divisors [1,3]. d=1: old cnt1=3 new=4 diff=4-3=1; total=15+1=16. d=3: old cnt3? After 6, cnt3=1? Actually 6 gave cnt3=1. So old=1 new=2 diff= comb[2]-comb[1]=2-1=1; phi3=2 => total=16+2=18. So total=18. Good.
Now add c=2: divisors [1,2]. d=1: old=4 new=5 diff=5-4=1 -> total=18+1=19; d=2: old cnt2 currently? After initial, cnt2: numbers divisible by 2 are 6,4 -> cnt2=2 (since 6 and 4). Also 2 itself divisible by 2. So old=2 new=3 diff= comb[3]-comb[2]=3-2=1; total=19+1=20. Output 20.
Add c=1: divisors [1]. d=1: old=5 new=6 diff=6-5=1; total=20+1=21. Output 21.
Matches.
So algorithm is correct.
Now, we need to consider large inputs: n,q up to 100k, numbers up to 1e6.
Now, we must ensure that the linear sieve for phi works correctly. Let's test some small values manually: For limit=10, compute phi using our linear sieve.
Initialize spf[0..10]=0, phi[0]=0, phi[1]=1.
Loop i=2:
spf[2]==0 => prime: spf[2]=2, primes=[2], phi[2]=1.
Then inner for p in primes: p=2, p>spf[i]? spf[2]=2, p=2 not >; i*p=4<=10, set spf[4]=2; i%p==0 => phi[4]=phi[2]2=12=2; break.
i=3:
spf[3]==0 => prime: spf[3]=3, primes=[2,3], phi[3]=2.
inner: p=2: p>spf[3]? spf[3]=3, 2 not >; ip=6<=10, set spf[6]=2; i%2!=0 => phi[6]=phi[3](2-1)=21=2.
next p=3: p>spf[3]? 3>3? false; ip=9<=10, set spf[9]=3; i%3==0 => phi[9]=phi[3]3=23=6; break.
i=4:
spf[4]==2 (already set) => not prime.
inner loop: p=2: p>spf[4]? spf[4]=2, 2 not >; i*p=8<=10, set spf[8]=2; i%2==0 => phi[8]=phi[4]2=22=4; break.
(since break after i%p==0)
i=5:
spf[5]==0 => prime: spf[5]=5, primes=[2,3,5], phi[5]=4.
inner: p=2: p>spf[5]? 2>5 false; ip=10<=10, set spf[10]=2; i%2!=0 => phi[10]=phi[5](2-1)=41=4.
p=3: 3>5 false; ip=15>10 break.
i=6:
spf[6]==2 => not prime.
inner: p=2: p>spf[6]? 2>2 false; ip=12>10 break? Actually 62=12>10, so break (since condition ip>limit, break). So no more.
i=7:
prime: spf[7]=7, phi[7]=6.
inner: p=2: 2>7 false; ip=14>10 break.
i=8:
spf[8]==2, not prime.
inner: p=2: p>2 false; ip=16>10 break.
i=9:
spf[9]==3, not prime.
inner: p=2: p>3? false; ip=18>10 break? Actually check: ip=92=18>10, so break.
i=10:
spf[10]==2, not prime.
inner: p=2: p>2 false; i*p=20>10 break.
Now phi: 1:1,2:1,3:2,4:2,5:4,6:2,7:6,8:4,9:6,10:4. This is correct. So linear sieve works.
Now, we need to ensure that phi[1]=1 is set. We set it before loop. Good.
Now, we also set phi[0]=0 but not used.
Now, about spf for 1: remains 0, but we never use.
Now, for numbers up to maxVal, we should compute spf correctly.
Now, for the divisor generation, we rely on spf. For x=1, while temp>1 loop won't run, divs remains [1]. That's fine.
Now, note: When we compute divisors, we use the list 'divs' and extend it. For numbers with many prime factors, this is okay.
Now, potential performance improvement: Since we call add_number many times, we could avoid building a list of divisors for each number and instead iterate directly using recursion to update cnt. But building list is simple.
Now, we need to consider that maxVal could be up to 1,000,000. Linear sieve loops 1e6 times; inner loop for each i iterates over primes until condition break. That's typical O(N). Should be fine (<0.1 sec in C++ but in Python maybe ~0.5-1 sec). Still okay.
Now, we need to also precompute factorials up to 200k, which is fast.
Now, overall time should be fine.
Now, we can further optimize by using local variables inside add_number for speed (like referencing global arrays as local). For example, we can assign to local variables: cnt_local = cnt, phi_local = phi, comb_local = comb, spf_local = spf, total (nonlocal). However, we can also restructure code to avoid function call overhead by inlining the update in the main loops. But that might reduce readability.
Given that add_number is called 200k times, function call overhead is not huge. But we can still keep it.
Alternatively, we can define it as inner function and use nonlocal total. That's okay.
But we also need to be careful about Python's scoping and variable lookups: Inside add_number, each reference to cnt, phi, comb, spf will be looked up from enclosing scope. That's fine but a bit slower. We could pass them as arguments? That would add argument passing overhead. Better to make them global variables? Then inside function we use global. That might be similar.
We can make them global by defining them at module level and using global statement. But then they are accessed faster? Actually, global variable lookup is also a dictionary lookup; local variable lookups are faster. In a function, if we assign them to local variables at the start, e.g., cnt = cnt_global, etc., then they become local. But we need to modify cnt array, which is mutable, so we can just have a reference. To speed up, we can do:
def add_number(x):
nonlocal total
local_cnt = cnt
local_phi = phi
local_comb = comb
local_spf = spf
# then use local_* inside.
But careful: local_cnt is a reference to the list, and assignments to its elements will modify the original. That's fine. However, we also need to assign to total (nonlocal). That's fine.
But I think it's okay without micro-optimizations. We'll see.
Now, check for potential errors: In get_divisors, we used variable 'temp' which we modify. But we also used 'x' as parameter; but we don't need x after. Good.
Now, think about large k: For k close to N_total, comb values for large m are computed. That's fine.
Now, check mod for comb: Since we compute comb using factorial and inv_fact, we need to ensure that inv_fact[m-k] exists. m-k could be as low as 0, we have inv_fact[0] = 1 (since we set inv_fact[0] via backward loop: for i in range(N_total,0,-1): inv_fact[i-1] = inv_fact[i] * i % MOD. So at the end, inv_fact[0] will be computed. Good.
Now, one nuance: For m = k, inv_fact[0] exists. So fine.
Now, consider the case where k > N_total? Not possible because k ≤ n ≤ n+q = N_total? Actually n ≤ N_total, and k ≤ n, so k ≤ N_total. So safe.
Now, we also need to consider that the numbers (a_i, c_j) may be up to 1e6, but we might have duplicates? Yes, counts for different species can be equal; they are distinct species but counts may be same. That's fine; they are treated as separate elements.
Now, we must consider that in the sum over subsets, species are distinct; we are counting subsets of indices. Our cnt_d counts the number of species whose count is divisible by d, regardless of duplicates. So C(cnt_d, k) counts subsets of distinct species. That's correct.
Now, we need to ensure that the modulo for negative diff works. In Python, (-1) % MOD = MOD-1, which is correct. However when we compute total = (total + phi[d] * diff) % MOD, if diff negative, product may be negative, and the final modulo yields correct residue. But we need to ensure that total is always an integer; it will be.
Now, an alternative to avoid negative is to compute diff_mod = (comb[new] - comb[old]) % MOD, then total = (total + phi[d] * diff_mod) % MOD. That adds one modulo per diff. Since number of diffs is ~ few million, this might add some overhead. But we can keep as is.
Now, test with scenario where diff negative: For example, when k=3, comb[4]=4, comb[5]=10, diff positive. For k=2, comb[5]=10, comb[4]=6? Actually C(4,2)=6, C(5,2)=10 diff=4 positive. Usually diff is positive because C(m,k) is increasing in m. So diff = comb[new] - comb[old] should be >=0? Because C(m,k) is increasing with m. However, comb[m] is C(m,k) modulo MOD, which for m from 0 to N_total, C(m,k) increases, but modulo representation also increases until it reaches MOD and then wraps? But C(m,k) can exceed MOD; it's not monotonic modulo MOD. For m such that C(m,k) is huge, taking modulo MOD may cause wrap-around, making comb[m] not monotonic. For example, MOD=7, k=1, comb[m] = m mod 7; that's increasing until 6 then wraps to 0. So comb[6]=6, comb[7]=0 (since 7 mod 7 = 0) so diff negative. Indeed, in our earlier examples for k=1, comb[6]=6, comb[7]=0 (if N_total >=7). But wait C(7,1)=7, mod 7 =0, so comb[7]=0, diff = 0-6 = -6. So diff can be negative! In our second sample, N_total=6, so we didn't see wrap. But for larger N_total, comb may wrap. So diff = comb[new] - comb[old] may be negative modulo. However, when we compute total = (total + phi[d] * diff) % MOD, it's equivalent to adding phi[d] * ( (C(new) - C(old)) mod MOD ) mod MOD, which is correct because we only care about sum modulo MOD. But we must ensure that our update formula using diff = comb[new] - comb[old] (the integer difference of residues) works modulo MOD. Since total is maintained modulo MOD, adding phi[d]diff and then mod is same as adding phi[d]((C(new)-C(old)) mod MOD) mod MOD. Because (total + phidiff) mod MOD = (total + phi( (C_new_mod - C_old_mod) )) mod MOD. But (C_new_mod - C_old_mod) may not equal (C_new - C_old) mod MOD? Actually (C_new_mod - C_old_mod) ≡ (C_new - C_old) (mod MOD) because C_new_mod ≡ C_new (mod MOD) and C_old_mod ≡ C_old (mod MOD). So (C_new_mod - C_old_mod) ≡ (C_new - C_old) (mod MOD). So phi * (C_new_mod - C_old_mod) ≡ phi * (C_new - C_old) (mod MOD). So adding this to total (which is mod MOD) and taking mod yields correct result. However, if we use diff = C_new_mod - C_old_mod (which could be negative) and we compute total + phidiff, and then mod, we effectively add phi * (C_new_mod - C_old_mod) which is congruent to phi(C_new - C_old) modulo MOD. So it's correct. But if we were to keep total as an integer not reduced mod MOD, then we would need actual integer difference, not just modded difference. However we maintain total modulo MOD, so it's fine. But careful: Our total is maintained modulo MOD (we apply % after each update). So after each addition, total is a residue. When we later add phidiff, we are adding a value that is congruent to phi(C_new - C_old) modulo MOD, but it may not be the exact integer difference. However, since total is only meaningful modulo MOD, it's fine. But we must ensure that we are consistent: The initial total after processing some numbers is Σ φ(d) * C(cnt_d,k) mod MOD. Then when we increment cnt[d] for a divisor, we want to update total to new_total = old_total + φ(d)*(C(new)-C(old)) mod MOD. If we compute diff_residue = (C_mod[new] - C_mod[old]) (which might be negative), then new_total_mod = (old_total_mod + φ(d) * diff_residue) mod MOD. Because φ(d)(C(new)-C(old)) (mod MOD), this gives correct new_total_mod. So it's valid.
Thus our update method is correct even when comb values wrap.
Now, we must also consider that we store comb as residues. So diff may be negative or positive. That's okay.
Now, we need to ensure that the initial total after processing initial numbers is computed correctly modulo MOD. In our code, we update total as we go, applying % each time. So final total is modulo MOD.
Now, output after each query is total % MOD, but total is already modulo, so output as is.
Now, we should test with a case where MOD wrapping occurs. For simplicity, let's test with small numbers but smaller MOD? Not possible because MOD is fixed. But we can test with a scenario where k=1, N_total > MOD. Actually MOD = 1e9+7, and N_total max 200k, so C(m,1) = m <= 200k, which is less than MOD, so no wrap for k=1. For k=2, C(200k,2) ≈ 2e10, which is about 20 billion, MOD 1e9+7, so it may exceed MOD and wrap. So diff can be negative. For example, if comb[2000] and comb[2001] might have wrap? Actually need to check: Since we only compute comb for m up to 200k, it's possible that for large m and k, C(m,k) mod MOD is not monotonic. So diff may be negative. Our code handles that.
Now, one more nuance: The formula sum = Σ φ(d) * C(cnt_d, k) is correct over integers. Modulo MOD, we compute Σ φ(d) * (C(cnt_d,k) mod MOD) mod MOD. That's correct because φ(d) is small, but we must take mod after multiplication.
Now, we need to ensure that phi[d] might be taken mod MOD as well, but it's less than MOD.
Now, the only potential issue is overflow of intermediate total before mod, but we mod frequently.
Now, let's test with a random small set and compare brute force.
We'll write a small Python script offline, but not needed now.
Now, we also need to consider that q can be 0? Problem says 1 ≤ q, so at least 1 query.
Now, we need to think about performance of linear sieve for maxVal=1e6. In Python, loops with many operations might be a bit slow but still okay. For typical CP, linear sieve for 1e6 in Python runs in about 0.3-0.5 seconds. Then divisor enumeration for 200k numbers ~ few million iterations, each with small loops; total maybe 1 second. Factorial precomputation 200k loops trivial. So overall maybe 2 seconds. Acceptable.
Now, we should also note that we could precompute all divisors for each possible number using a sieve-like method: For d from 1 to maxVal, for multiple m of d, add d to list of divisors of m. This would produce a list of divisors for each number, which we could store in a list of lists. The total number of entries is sum_{i=1}^{maxVal} d(i) ≈ maxVal * log maxVal + (2γ-1) maxVal ~ 14e6 for maxVal=1e6. That's about 14 million ints. Storing as list of lists would have overhead per list (each list object overhead). Not ideal. But generating on the fly is fine.
Now, we should also consider that we can reuse divisor generation: For each x, we generate its divisors. The number of divisors is small.
Now, we need to ensure that in add_number, we don't accidentally include 0 as divisor. No.
Now, think about potential bug: The linear sieve sets spf for composites but we rely on spf array to factor numbers. In our linear sieve, we break after i%p==0. That's standard.
Now, for numbers that are prime, spf[i] = i. Good.
Now, for factorization: while temp > 1: p = spf[temp]; then while temp % p == 0: temp //= p. This works because after dividing out all p, temp becomes smaller and its spf may be larger prime? Actually after dividing out all p, temp becomes temp' that is not divisible by p. Then we get next p = spf[temp'], which is the next smallest prime factor of the original number (since we process in increasing order). Works.
Now, we need to be careful about spf for 1: we set spf[1] maybe 0, but we never access because temp becomes 1 and loop stops.
Now, we should consider performance of while loops for factorization: For each number, we may divide multiple times. Number of divisions is sum of exponents, which is at most about log2(x) (worst-case for powers of 2, 20 divisions). So cheap.
Now, everything seems good.
Now, we must double-check the correctness of phi generation: linear sieve's phi computation is standard.
Now, we also need to ensure that phi[0] is not used; but for d=0 we never use.
Now, code.
Potential optimization: In add_number, we can avoid building list of divisors if we use recursion to update cnt directly. But it's fine.
Now, we should test with max constraints to ensure no recursion depth issues.
Now, final code.
But before finalizing, we can consider an alternative approach: Instead of maintaining cnt array for all d up to maxVal, we could maintain for each d only when cnt[d] changes. But we already have that.
Now, some final checks:
-
Input reading: we used iter(data) to get values. That's fine.
-
maxVal might be 0 if no numbers? Not possible because n>=1.
-
If k > N_total? Not possible.
-
comb array: we compute using loop from k to N_total. For large k near N_total, that loop is small.
-
In add_number, we use nonlocal total. This is valid inside nested function.
Now, we can also micro-opt: Precompute inv_fact_k and use it in comb computation, which we already did.
Now, after building comb, we no longer need fact and inv_fact. We could delete them to free memory, but not needed.
Now, we can also precompute phi_mod? Not needed.
Now, output: join lines and write.
Now, test with sample inputs.
Let's quickly simulate in mind or we can trust.
Now, I'll produce final answer.
But before final, consider potential integer overflow in computing mul *= p for exponent; p up to 1e6, exponent maybe up to ~20 (since 2^20 ~ 1e6). mul could become up to 1e6. Python handles.
Now, we might want to use local variable references inside add_number for speed: assign global arrays to local variables.
Let's rewrite add_number as:
def add_number(x):
nonlocal total
local_cnt = cnt
local_phi = phi
local_comb = comb
local_spf = spf
divs = [1]
temp = x
while temp > 1:
p = local_spf[temp]
exp = 0
while temp % p == 0:
temp //= p
exp += 1
cur_len = len(divs)
mul = 1
for _ in range(exp):
mul *= p
for i in range(cur_len):
divs.append(divs[i] * mul)
for d in divs:
old = local_cnt[d]
new = old + 1
total = (total + local_phi[d] * (local_comb[new] - local_comb[old])) % MOD
local_cnt[d] = new
But note: local_cnt is a reference to cnt; assigning to local_cnt[d] modifies cnt. Good.
This may give some speed.
Now, we also need to consider that total is nonlocal, and we update it.
Now, we also may consider that we can avoid building list 'divs' by using recursion to iterate over divisors and update directly. However, building list is simple.
Now, we need to ensure that we don't hit recursion limit.
Now, the code should pass.
Now, let's think about possible bug: In the linear sieve, we set phi[i] for i prime as i-1. For i=2, that's 1; correct. But for i=1 we set manually.
Now, for i up to maxVal, we might have phi[0] remains 0. That's fine.
Now, check if we need to set phi for numbers that are not covered by the sieve? The loop goes to maxVal, so all covered.
Now, we need to make sure we set phi[1]=1. We did before loop.
Now, also need to set spf[0]=0, spf[1]=0? Not necessary.
Now, now about modulo: total = (total + phi[d] * (comb[new] - comb[old])) % MOD. Since comb[new] - comb[old] can be negative large, product could be negative large, but modulo will correct. However, Python's % with negative numbers yields a positive remainder, but if the product is -1e15, then (total + negative) % MOD may be slower? But still okay.
Alternatively, we could compute diff = (comb[new] - comb[old]) % MOD, then total = (total + phi[d] * diff) % MOD. This avoids large negatives and may be faster due to smaller intermediate? Actually diff mod MOD is between 0 and MOD-1, so product is positive, but we have to compute diff_mod which involves a modulo operation. Which is more expensive? Modulo is relatively expensive. So keeping as is may be better because we already do modulo at the end. However, if the sum becomes negative huge, Python big ints may be slower. But likely not significant.
We can test: For worst-case diff = -1e9, phi up to 1e6, product -1e15, total up to MOD ~1e9, adding yields ~ -1e15, then modulo operation involves division. That's okay.
Given number of updates ~ few million, it's fine.
Now, let's double-check the loop for generating divisors: we used "for i in range(cur_len):" inside "for _ in range(exp):". This will generate all divisors, but note that for each exponent step, we multiply existing base divisors by p^e. However, typical algorithm: for each prime factor (p, exp), we take the current list of divisors, and for e from 1 to exp, multiply each existing divisor by p^e and append. The way we wrote: cur_len = len(divs) before processing this prime factor. Then for each exponent step, we compute mul (starting at 1 then multiply by p each iteration). For the first iteration (e=1), mul = p; we loop over indices 0..cur_len-1 and append divs[i]p. For second iteration (e=2), mul = pp; we again loop over same original set (0..cur_len-1) and append divs[i]*p^2. This correctly generates all combinations because we only multiply original divisors by p^e, not those newly added from this prime factor? Actually careful: When generating divisors for a number, we need to combine all existing divisors with each power of the prime. The typical method: Start with [1]. For each (p, exp), for each current divisor in the list (including those added from previous primes), multiply by p^e for e=1..exp and add to list. However, if we fix cur_len before processing the prime, and then iterate over e, and for each e we iterate over indices 0..cur_len-1 (the original list before any new appends for this prime), we are only multiplying the divisors that existed before processing this prime. But after we process e=1, we have appended new divisors that include factor p^1. For e=2, if we multiply only the original ones by p^2, we miss combinations where we have p^1 from the first exponent and then multiply by p? Actually the full set of divisors for prime p^exp should be: for each existing divisor d (from previous primes), we can multiply by p^0, p^1, ..., p^exp. The algorithm that takes current list (including previous primes) and then for e=1..exp, for each divisor in the original list (before processing this prime), multiply by p^e and append, works because the new divisors with p^e are generated from the original set. But we also need to consider that after appending p^1 divisors, these new divisors should also be multiplied by higher powers? No, because p^1 * p^1 would give p^2, but that would be the same as original divisor * p^2. However, is it possible to have a divisor that contains p^1 from this prime and also other primes? That divisor would be generated as original divisor (which may include other primes) times p^1. Then for higher powers, we need to also consider taking that new divisor and multiply by p again? Actually, if we multiply original divisor by p^1 to get a divisor with p^1, then to get a divisor with p^2, we could either multiply original divisor by p^2, or multiply the divisor with p^1 by p. But the set of divisors is just all products of original divisor (from previous primes) and p^e for e=0..exp. So it's sufficient to generate from the original set only. Because any divisor can be uniquely expressed as original divisor (which contains contributions from previous primes) times p^e. So we don't need to multiply the newly generated ones again. Therefore, using the original list (before processing this prime) is correct. So our algorithm is correct. However, we must ensure that we don't multiply the newly added divisors from this prime again, because that would cause duplicates. By using cur_len fixed before the loop, we avoid that. So it's fine.
Now, test with number 12 = 2^2 * 3. Start divs=[1]. Process p=2, exp=2: cur_len=1.
e=1: mul=2, append 12=2 -> divs=[1,2]
e=2: mul=4, append 14=4 -> divs=[1,2,4]
Now process p=3, exp=1: cur_len=3 (current length). mul=3, for i=0..2: append divs[i]3 -> 13=3, 23=6, 43=12. Result divisors: [1,2,4,3,6,12] correct. Good.
Now, for number with repeated primes, algorithm works.
Thus divisor generation correct.
Now, consider if we have number with a prime factor that appears multiple times, like 8=2^3. Start [1]; cur_len=1; e=1 mul=2 -> [1,2]; e=2 mul=4 -> [1,2,4]; e=3 mul=8 -> [1,2,4,8]; correct.
Now, code looks good.
Now, potential issue: In add_number, after we generate divisors, we update cnt and total. However, we must ensure that we update cnt[d] after processing all divisors? Actually we update each d sequentially. Order doesn't matter.
Now, we also need to ensure that we don't double count something? No.
Now, edge case: k > current number of species? But after each insertion, number of species increases. Initially, we have n species, and k ≤ n, so fine. After each insertion, n+j >= n >= k. So no issue.
Now, we should also consider if k=0? Not allowed.
Now, final answer.
But we need to be careful about reading input: after reading n, k, q, we read n lines each with an integer, and q lines each with an integer. The input format: each on separate line. Our method using split works regardless.
Now, potential memory for data list: (n+q+3) integers, up to 200k+3, fine.
Now, we should run a quick test with a random small case to ensure no errors.
Let's do mental test: n=1, k=1, q=1, a=[5], c=[3]. Initially total after processing 5: divisors [1,5]; update: d=1: old=0 new=1 diff=comb[1]-comb[0]=1-0=1 phi1=1 total=1; d=5: diff=1 phi5=4 total=5. So total=5. Then add 3: divisors [1,3]; d=1: old=1 new=2 diff=2-1=1 total=6; d=3: diff=1 phi3=2 total=8. Output 8. Subsets: after both numbers, subsets of size1: {5} and {3} => sum=8. correct.
Now test n=2, k=2, q=0 (though q≥1). Not needed.
Now, we should also test with large k e.g., n=5, k=5, q=0? not needed.
Now, all good.
Now, consider case where some numbers are 1. That's fine.
Now, one more nuance: The numbers ai and cj are up to 1e6, but what about the gcd? The gcd of a subset can be up to 1e6, but we sum them, but modulo.
Now, final code.
I'll produce final answer.
But before final, we should double-check the linear sieve for phi: In our loop we used if spf[i] == 0 to detect prime. However, we initialized spf as list of zeros. For i=2, spf[2] is 0, so we set it to i and phi[i]=i-1. Then inner loop for primes: for p in primes: check if p > spf[i] or ip > limit: break. For prime i, spf[i] = i, so p > spf[i]? For first p (2), p=2, spf[2]=2, 2>2 false. So we compute ip. For i=2, i*p=4, set spf[4]=2; then i%p ==0, so break. Good.
For i=3: primes [2,3]. p=2: p>spf[3]? spf[3] now is? At this point, before prime detection, spf[3] is 0? Actually i=3, we first check if spf[3]==0 => true, so we set spf[3]=3, primes append 3, phi[3]=2. Then we go to inner loop. Now primes = [2,3] (since we appended 3). Then for p in primes: first p=2. p>spf[3]? spf[3]=3, 2>3 false. Compute ip=6, set spf[6]=2, i%2!=0 so phi[6]=phi[3](2-1)=2. Next p=3: p>spf[3]? 3>3 false. Compute i*p=9, set spf[9]=3, i%3==0 => phi[9]=phi[3]*3=6, break. Good.
For i=4: spf[4] already set to 2, so not prime. Then inner loop: primes = [2,3]. p=2: p>spf[4]? spf[4]=2, 2>2 false. Compute ip=8, set spf[8]=2, i%2==0 => phi[8]=phi[4]2= ? But what is phi[4]? At this point, phi[4] should have been set earlier when i=4? Wait we are processing i=4 now, but phi[4] hasn't been computed yet because we didn't compute phi for i=4 as prime. But we need phi[4] to compute phi[8]. However, in linear sieve, phi is computed for all numbers as we go: when we process i, we have already computed phi[i] because we either set it as prime (phi[i]=i-1) or it was set as phi for composite? For composite numbers, phi[i] should have been set when i was produced as i = (some previous i') * p. In our loop, when we set spf[ip] and phi[ip], we assign phi for i*p. So when we get to i=4, phi[4] should already have been set when i=2 (i=2, p=2 produced 4 and set phi[4]=phi[2]*2=2). Indeed, earlier when i=2, we set phi[4]=2. So phi[4] exists. Good.
Thus phi[4] is available. Then phi[8] = phi[4]*2 = 4. Works.
So linear sieve works.
Now, we must ensure that for i=1 we set phi[1]=1. We did before loop.
Now, note: For i=0, we didn't set phi[0] but not used.
Now, we can finalize.
One more thing: In the linear sieve, we use condition 'if spf[i] == 0:' to detect prime. But we didn't set spf[1] to 1, so spf[1]==0. However, we start loop from i=2, so fine.
Now, after sieve, we might have spf[0] and spf[1] still 0, but we never use them.
Now, final code.
Potential performance issue: In add_number, we allocate a new list 'divs' for each number. For numbers with many divisors, that's fine. But we also allocate many lists (200k). That could cause memory churn, but Python's garbage collector will handle. We could reuse a list by clearing but not necessary.
Alternatively, we could generate divisors and directly update without storing whole list, using recursion, but it's okay.
Now, we should test with maximum scenario: n=100k, q=100k, all numbers random up to 1e6. Approx total divisor enumeration 2.8 million (since average divisor count ~14). So list allocations 200k lists of average size 14, that's ~2.8 million integers stored overall but each list is temporary. That's fine.
Now, final answer.
Now, we produce final solution.
But wait, the problem statement says "After receiving flowers on each of these q days, Farmer John would like to know the sum, over all possible choices of k species, of the maximum number of gardens he could create." That's exactly what we computed.
Now, we must output after each day modulo 1e9+7.
Now, everything is consistent.
Thus final code is as described.
Now, we should write final answer in response.
But as ChatGPT, I need to output the final code.
I'll write the final code with careful formatting. ```python
import sys
MOD = 10 ** 9 + 7
def main():
data = list(map(int, sys.stdin.buffer.read().split()))
it = iter(data)
n = next(it)
k = next(it)
q = next(it)
a = [next(it) for _ in range(n)]
c = [next(it) for _ in range(q)]
max_val = max(a + c) if (a or c) else 1
total_cnt = n + q # maximum number of species
# ---------- linear sieve for spf and phi ----------
spf = [0] * (max_val + 1)
phi = [0] * (max_val + 1)
primes = []
phi[0] = 0
phi[1] = 1
for i in range(2, max_val + 1):
if spf[i] == 0: # i is prime
spf[i] = i
primes.append(i)
phi[i] = i - 1
for p in primes:
if p > spf[i] or i * p > max_val:
break
spf[i * p] = p
if i % p == 0:
phi[i * p] = phi[i] * p
break
else:
phi[i * p] = phi[i] * (p - 1)
# ---------- precompute C(m, k) for m = 0..total_cnt ----------
fact = [1] * (total_cnt + 1)
for i in range(1, total_cnt + 1):
fact[i] = fact[i - 1] * i % MOD
inv_fact = [1] * (total_cnt + 1)
inv_fact[total_cnt] = pow(fact[total_cnt], MOD - 2, MOD)
for i in range(total_cnt, 0, -1):
inv_fact[i - 1] = inv_fact[i] * i % MOD
comb = [0] * (total_cnt + 1)
if k <= total_cnt:
inv_fact_k = inv_fact[k]
for m in range(k, total_cnt + 1):
comb[m] = fact[m] * inv_fact_k % MOD * inv_fact[m - k] % MOD
# ---------- frequency of numbers divisible by d ----------
cnt = [0] * (max_val + 1)
total = 0 # current answer modulo MOD
# ---------- helper to insert a new number ----------
def add_number(x: int):
nonlocal total
# generate all divisors of x using its prime factorization
divs = [1]
tmp = x
while tmp > 1:
p = spf[tmp]
exp = 0
while tmp % p == 0:
tmp //= p
exp += 1
cur_len = len(divs)
mult = 1
for _ in range(exp):
mult *= p
for i in range(cur_len):
divs.append(divs[i] * mult)
# update for every divisor d
for d in divs:
old = cnt[d]
new = old + 1
total = (total + phi[d] * (comb[new] - comb[old])) % MOD
cnt[d] = new
# ---------- initial species ----------
for val in a:
add_number(val)
# ---------- answer after each day ----------
out = []
for val in c:
add_number(val)
out.append(str(total))
sys.stdout.write("\n".join(out))
if name == "main":
main()