您的位置:首页 > 编程语言 > Java开发

java编程实现杨辉三角(摘自java核心技术.卷I)

2013-08-18 16:14 423 查看
/**

* This program demonstrates a triangular array.

* @version 1.20 2004-02-10

* @author Cay Horstmann

*/

public class LotteryArray

{

public static void main(String[] args)

{

final int NMAX = 10;//行数

// allocate triangular array

int[][] odds = new int[NMAX + 1][];

for (int n = 0; n <= NMAX; n++)

odds
= new int[n + 1];

// fill triangular array

for (int n = 0; n < odds.length; n++)

for (int k = 0; k < odds
.length; k++)

{

/*

* compute binomial coefficient n*(n-1)*(n-2)*...*(n-k+1)/(1*2*3*...*k)

*/

int lotteryOdds = 1;

for (int i = 1; i <= k; i++)

lotteryOdds = lotteryOdds * (n - i + 1) / i;//第一次知道杨辉三角原来和二项式系数这么联系紧密,杨辉三角的第n行原来就是二项式展开式系数的前n项。

odds
[k] = lotteryOdds;

}

// print triangular array

for (int[] row : odds)

{

for (int odd : row)

System.out.printf("%4d", odd);

System.out.println();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: