日期:2014-05-20 浏览次数:20744 次
public class YangHuiTriangle { private int n;// 表示行 public YangHuiTriangle(int n) { this.n = n; } public void printYangHuiTriangle() { System.out.println("杨辉三角(" + n + ")层:"); System.out.println(1); for (int i = 1; i <= n - 1; i++) { for (int j = 0; j <= i; j++) { if (j == 0) System.out.print(1 + "\t"); else { System.out.print(calc(i, j) + "\t"); } } System.out.println(); } } //计算i行j列上的值,i,j从0开始 public long calc(int i, int j) { double a = 1.0;//i行j列上的值 for (int k = 1; k <= j; k++) { a *= (double)i / k; i--; } return (long)a; } public static void main(String[] args) { YangHuiTriangle y = new YangHuiTriangle(20); y.printYangHuiTriangle(); } }
public class YangHuiTriangle { private int n;// 表示行 public YangHuiTriangle(int n) { this.n = n; } public void printYangHuiTriangle() { System.out.println("杨辉三角(" + n + ")层:"); for (int i = 0; i < n ; i++) { for (int j = 0; j <= i; j++) { System.out.print(calc(i, j) + "\t"); } System.out.println(); } } //递归计算C(i,j) = 1 (k=0或者j=i);C(i,j) = C(i-1,j-1) + C(i-1,j) public long calc(int i, int j) { if (( j == 0 ) || (j == i)) return 1; return calc(i-1, j-1) + calc(i-1, j); } public static void main(String[] args) { YangHuiTriangle y = new YangHuiTriangle(20); y.printYangHuiTriangle(); } }
------解决方案--------------------
数字太大了,用BigInteger即可。
import java.math.BigInteger; public class YangHuiTriangle { private int n;// 表示行 public YangHuiTriangle(int n) { this.n = n; } public void printYangHuiTriangle() { System.out.println("杨辉三角(" + n + ")层:"); System.out.println(1); for (int i = 1; i <= n - 1; i++) { for (int j = 0; j <= i; j++) { if (j == 0) System.out.print(1 + "\t"); else { System.out.print(calc(i, j) + "\t"); } } System.out.println(); } } //计算i行j列上的值,i,j从0开始 public BigInteger calc(int i, int j) { BigInteger a = new BigInteger("1") ;//i行j列上的值 for (int k = 1; k <= j; k++) { a = a.multiply(new BigInteger(String.valueOf(i))).divide(new BigInteger(String.valueOf(k))); i--; } return a; } public static void main(String[] args) { YangHuiTriangle y = new YangHuiTriangle(20); y.printYangHuiTriangle(); } }