简短的杨辉三角C++实现
注意:需要C++11的支持
一、思想
∵
\because
∵
(
k
n
)
=
n
!
k
!
×
(
n
−
k
)
!
\binom{k}{n}=\frac{n!}{k!\times (n-k)!}
(nk)=k!×(n−k)!n!
又
(
k
+
1
n
)
=
n
!
(
k
+
1
)
!
×
(
n
−
k
−
1
)
!
\binom{k+1}{n}=\frac{n!}{(k+1)!\times (n-k-1)!}
(nk+1)=(k+1)!×(n−k−1)!n!
∴
\therefore
∴
(
k
+
1
n
)
=
(
k
n
)
×
n
−
k
k
+
1
\binom{k+1}{n}=\binom{k}{n}\times\frac{n-k}{k+1}
(nk+1)=(nk)×k+1n−k
二、源代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
auto num = 0;
cout << "Please input the num:" << endl;
cin >> num;
for (auto row = 0; row < num; ++row) {
auto temp = 1;
for (auto space = 0; space < num - row; ++space) {
cout << setw(2) << " ";
}
for (auto col = 0; col <= row; ++col) {
cout << " " << setw(4) << temp;
temp = temp * (row - col) / (col + 1);
}
cout << endl;
}
cout << endl;
return 0;
}