JS中的楊輝三角

JS中的楊輝三角

楊輝三角

楊輝三角使用二維數組

var n=Number(prompt(“請輸入楊輝三角的行數”));
document.write(" < center> “);//居中
var arr = []; //先聲明一維
for (var i = 0; i < n; i++) { //一維長度
arr[i] = []; //在聲明二維
for (var j = 0; j <= i ; j++) {
if (i == j || j == 0) {//讓每一行的第一個和最後一個等於1
arr[i][j] = 1;
}
else {
arr[i][j] = arr[i-1][j-1] + arr[i-1][j];
}
document.write(” “+arr[i][j]+” “);
}
document.write(”
");

}
楊輝三角使用遞推

var n=Number(prompt(“請輸入楊輝三角的行數”)); //楊輝三角,N爲行數
document.write("< center>");
for( var i = 1 ; i <= n ; i++ ){
for ( var j = 1 ; j <= i ; j++ ) {
document.write(Combination(i,j)+" “);
}
document.write(”
");
}

function Combination(x,y){
if(y == 1) return 1; //每行第一個數爲1
else if(x == y) return 1; //最後一個數爲1
else return Combination(x-1,y-1)+Combination(x-1,y);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章