用多种程序语言编写杨辉三角
时间: 2024-11-04 14:11:37 浏览: 5
杨辉三角是一个数学术语,它是一种二项式系数的几何排列形式,常用于组合数学和概率论中。我们可以用多种编程语言来展示杨辉三角,下面分别给出Python和JavaScript的例子:
**Python**
```python
def print_pascal_triangle(n):
triangle = [[1]]
for _ in range(1, n):
new_row = [1]
for j in range(1, len(triangle[-1]) - 1):
new_row.append(triangle[-1][j] + triangle[-1][j - 1])
new_row.append(1)
triangle.append(new_row)
for row in triangle:
print(' '.join(str(num) for num in row))
# 打印前5行杨辉三角
print_pascal_triangle(5)
```
**JavaScript**
```javascript
function generatePascalTriangle(n) {
let triangle = [[]];
for (let i = 0; i < n; i++) {
let newRow = [1];
for (let j = 0; j <= i; j++) {
if (j === 0 || j === i) newRow.push(1);
else newRow.push(triangle[i - 1][j - 1] + triangle[i - 1][j]);
}
newRow.push(1);
triangle.push(newRow);
}
return triangle;
}
// 输出前5行杨辉三角
generatePascalTriangle(5).map(row => row.join(' ')).forEach(row => console.log(row));
```
阅读全文