1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
上面的图形熟悉吗?它就是我们中学时候学过的杨辉三角。
输入数据包含多组测试数据。
每组测试数据的输入只有一个正整数n(1≤n≤128),表示将要输出的杨辉三角的层数。
输入以0结束
对应于每一个输入,请输出相应层数的杨辉三角,每一层的整数之间用一个空格隔开,每一个杨辉三角后面加一个空行。
2 3 0
1 1 1 1 1 1 1 2 1
Java
//BigInteger
//开好数组后,从上往下扫描只扫描一次
//凡涉及大数复杂度的,提交前先自己用System.currentTimeMillis()测测时间
import java.math.BigInteger;
import java.util.Scanner;
public class 杨辉三角 {
public static void main(String[] args) { Scanner sc=new Scanner(System.in); while(sc.hasNext()){ int n=sc.nextInt(); if(n==0){ break; } BigInteger[][] array=new BigInteger[n][1]; for(int i=1;i<=n;i++){ array[i-1]=new BigInteger[i]; } for(int i=0;i<array.length;i++){ array[i][0]=BigInteger.ONE; array[i][array[i].length-1]=BigInteger.ONE; System.out.print(array[i][0]+" "); for(int j=1;j<array[i].length-1;j++){ array[i][j]=array[i-1][j].add(array[i-1][j-1]); System.out.print(array[i][j]+" "); } if(i==0){ System.out.println(); }else{ System.out.println(1); } } System.out.println(); } sc.close(); }
}
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int n = sc.nextInt();
if(n == 0) break;
BigInteger[][] arr = new BigInteger[n][n];
for (int i = 0; i < n; i ++ ) {
arr[i][0] = BigInteger.valueOf(1);
for (int j = 1; j < i + 1; j ++ ) {
if(j == i) arr[i][j] = arr[i][0];
else arr[i][j] = arr[i - 1][j - 1].add(arr[i - 1][j]);
}
}
for (int i = 0; i < n; i ++ ) {
for (int j = 0; j < i + 1; j ++ ) {
if(j == i) System.out.println(arr[i][j]);
else System.out.print(arr[i][j] + " ");
}
}
System.out.println();
}
}
}