I want to calculate the number of different ordered groups of N integers so that the elements of each group sums up to A
For instance: if N = 3 and A = 3 the result should be 10:
1 = [3, 0, 0]
2 = [2, 1, 0]
3 = [1, 2, 0]
4 = [0, 3, 0]
5 = [2, 0, 1]
6 = [1, 1, 1]
7 = [0, 2, 1]
8 = [1, 0, 2]
9 = [0, 1, 2]
10 = [0, 0, 3]
the way I did it was by brute-force:
public static int calc(int a, int n){
if (n <= 1 || a == 0) return 1;
int sum = 0;
for (int i=0; i<=n; i++)
sum += calc(a - i, n - 1);
return sum;
}
i suspect that there can be a better way (some mathematical calculation that I missing..) is there?
EDIT In the original question i forgot to take into consideration the order
This is combinatorial composition of A into N parts (including zero parts). Number of compositions for pair (A, N) is equal to C(A + N - 1, A), where C() is combination number aka binomial coefficient. See the same formula here and here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With