二项式系数数组 [英] Array of binomial coefficients

查看:70
本文介绍了二项式系数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我已经实现了二项式系数

So, I have implemented the binomial coefficient

public static int binomial(int n, int k) {
    if (k == 0)
        return 1;
    else if (k > n - k)
        return binomial(n, n - k);
    else
        return binomial(n - 1, k - 1) * n / k;
}

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);

    System.out.println("Insert n: ");
    int n = scan.nextInt();

    System.out.println("Insert k: ");
    int k = scan.nextInt();

    System.out.println("Result: " + binomial(n, k));
}

它有效,但是我遇到的困难只是我需要为两个给定的数字添加系数数组.因此,如果 n 5 k 3 .系数数组将显示: 1 5 10 10 .有什么想法吗?

And it works, but where I'm stuck is just that I need to add the coefficient array for two given numbers. So If n is 5 and k is 3. The coefficient array will display: 1 5 10 10. Any ideas?

推荐答案

所有您需要做的就是将表达式放入循环中并保持 n 不变.

All you need to do is put your expression in a loop and hold n constant.

for (int k = 0; k <= n; k++) {
    System.out.print(binomial(n, k) + " ");
}

如果愿意,可以将这些值存储在数组中.无需使您的方法更加复杂.

You can store these values in an array if you like. There is no need to make your method any more complicated.

如果要将其放入数组中,这是一种简单的方法.

If want to put it in an array, here is one easy way to do it.

int coefs[] = IntStream.rangeClosed(0, n).map(k -> binomial(n, k)).toArray();

coefs[] = [1, 5, 10, 10, 5, 1]

这篇关于二项式系数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆