The question was to calculate the number of binomial coefficients not divisible by a given prime number. For example:
For
num = 5
andprime = 5
, the output should be:countingBinomialCoefficient(num, prime) = 17 N = 0: [1] N = 1: [1, 1] N = 2: [1, 2, 1] N = 3: [1, 3, 3, 1] N = 4: [1, 4, 6, 4, 1] N = 5: [1, 5, 10, 10, 5, 1]
In the above example only 5, 10, 10, 5 are only divisible out of the 21 numbers. So the output is 17
The code I wrote is as follows:
long countingBinomialCoefficient(int num, int prime) {
long count = 0;
for (int i = 0; i <= num; i++) {
long nCk = 1;
for (int j = 0; j <= i; j++) {
if (nCk % prime != 0) count++;
nCk = nCk * (i - j) / (j + 1);
}
}
return count;
}
This proper output for two cases:
1. countingBinomialCoefficient(5, 5) = 17
and
2.countingBinomialCoefficient(5, 7) = 21
But it says time limit(=3000 ms) exceeded in case of
countingBinomialCoefficient(999999999, 7) in which case output should be 2129970655314432
Is there any error in my code? Are there any other shorter methods for this? Please help. Thanks in advance.