简体   繁体   English

计算二项式系数时超出时间限制(帕斯卡三角)

[英]Time limit exceeding in calculating binomial coefficients (Pascal's Triangle)

The question was to calculate the number of binomial coefficients not divisible by a given prime number.问题是计算不能被给定素数整除的二项式系数的数量。 For example:例如:

For num = 5 and prime = 5 , the output should be:对于num = 5prime = 5 ,输出应该是:

 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.在上面的例子中,只有5, 10, 10, 5只能在21 个数字中整除。 So the output is 17所以输出是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 1. countingBinomialCoefficient(5,5)= 17
and
2. countingBinomialCoefficient(5, 7) = 21 2. countingBinomialCoefficient(5,7)= 21

But it says time limit(=3000 ms) exceeded in case of但它说超过了时间限制(= 3000 ms),以防万一
countingBinomialCoefficient (999999999, 7) in which case output should be 2129970655314432计数BinomialCoefficient (999999999, 7) 在这种情况下输出应该是2129970655314432
Is there any error in my code?我的代码有错误吗? Are there any other shorter methods for this?还有其他更短的方法吗? Please help.请帮忙。 Thanks in advance.提前致谢。

To reduce the computation time of this code , you can first replace the outer loop with a parallel stream .要减少此代码的计算时间,您可以先用parallel替换外循环。 This can cut the time in half or more.这可以将时间减少一半或更多。

To further reduce the time, you can share the computation between different machines by dividing the range of rows for the computation and summing the results.为了进一步减少时间,您可以通过划分计算的行范围并对结果求和来共享不同机器之间的计算。

static long countingBinomialCoefficient(int num, int prime) {
    return IntStream.rangeClosed(0, num)
            .parallel()
            .mapToLong(i -> {
                long count = 0;
                long nCk = 1;
                for (int j = 0; j <= i; j++) {
                    if (nCk % prime != 0) count++;
                    nCk = nCk * (i - j) / (j + 1);
                }
                return count;
            }).sum();
}
// test failed in my case on one computer
public static void main(String[] args) {
    long time = System.currentTimeMillis();
    System.out.println(countingBinomialCoefficient(99999, 7)); // 2214367021
    System.out.println(System.currentTimeMillis() - time); // 24941
}

See also: Parallelized Matrix Multiplication另请参阅:并行矩阵乘法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM