杨辉三角
杨辉三角的每行满足当n=k时,Cnk各项的系数
所以我们先求Cnk各项的系数
代码:
import java.util.Scanner;
public class fiftyseven {
public static void main(String[] args) {
Scanner reader=new Scanner(System.in);
int n=reader.nextInt();
int k=reader.nextInt();
int fenzi,fenmu;int njie=1,kjie=1,nkjie=1;
int c=0;
for(int i=2;i<=n;i++) {
njie*=i;
}
for(int i=0;i<=k;i++) {
nkjie=1;
for(int j=1;j<=n-i;j++) {
nkjie*=j;
}
if(i==0) {
c=1;
}
else if(i==n) {
c=1;
}
else {
kjie*=i;
c=njie/(kjie*nkjie);
}
System.out.printf("%d ",c);
}
}
}
运行结果:
由此写出杨辉三角代码:
//杨辉三角
//想输出a[0]-a[4]行就输入4
import java.util.Scanner;
public class fiftyeight {
public static void main(String[] args) {
Scanner reader=new Scanner(System.in);
int w=reader.nextInt();
int njie=1,kjie=1,nkjie=1;
int c=0;
for(int p=0;p<=w;p++) {
njie=1;kjie=1;
for(int i=2;i<=p;i++) {
njie*=i;
}
for(int i=0;i<=p;i++) {
nkjie=1;
for(int j=1;j<=p-i;j++) {
nkjie*=j;
}
if(i==0) {
c=1;
}
else if(i==p) {
c=1;
}
else {
kjie*=i;
c=njie/(kjie*nkjie);
}
System.out.printf("%d ",c);
}
System.out.println();
}
}
}
运行结果: