Ive need this in some problems, but I can't figure out how to count it. I will be glad to useful ideas.
How many different arrays of length n are there of non-negative integers with sum of k; n <= 10^5, k <= 10^9
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 150 |
Ive need this in some problems, but I can't figure out how to count it. I will be glad to useful ideas.
How many different arrays of length n are there of non-negative integers with sum of k; n <= 10^5, k <= 10^9
Name |
---|
https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)
Stars and Bars
We can solve this problem using combinatorics.
Consider the "stars and bars" method. Imagine you have k stars and n-1 bars. The stars represent the sum, and the bars divide these stars into n parts (each part corresponds to an element of the array).
The total number of ways to arrange the k stars and n-1 bars is the number of ways to choose (n-1) positions for the bars among (k+n-1) total positions.
This is a combinatorial problem and can be solved using the binomial coefficient, often denoted as "n choose k" or C(n, k), which is given by: C(n, k) = n! / (k!(n-k)!)
In this case, we want to calculate C(k+n-1, n-1). The result may be very large, so you might need to calculate it modulo some number (e.g., 10^9 + 7).
It's worth noting that given the size of $$$k$$$ in the given problem, using the factorial formula directly is likely to be too slow when computing the answer modulo, say, $$$10^9 + 7$$$.
Instead, rewrite the formula without factorials, with a product of $$$(n - 1)$$$ terms in both the numerator and denominator — since $$$n$$$ is small, the two can be evaluated fast enough.