-
Notifications
You must be signed in to change notification settings - Fork 51
/
PascalsTriangle.cpp
51 lines (44 loc) · 935 Bytes
/
PascalsTriangle.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// C++ code for Pascal's Triangle
#include <iostream>
using namespace std;
// See https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/
// for details of this function
int binomialCoeff(int n, int k);
// Function to print first
// n lines of Pascal's
// Triangle
void printPascal(int n)
{
// Iterate through every line and
// print entries in it
for (int line = 0; line < n; line++)
{
// Every line has number of
// integers equal to line
// number
for (int i = 0; i <= line; i++)
cout <<" "<< binomialCoeff(line, i);
cout <<"\n";
}
}
// See https://www.geeksforgeeks.org/space-and-time-efficient-binomial-coefficient/
// for details of this function
int binomialCoeff(int n, int k)
{
int res = 1;
if (k > n - k)
k = n - k;
for (int i = 0; i < k; ++i)
{
res *= (n - i);
res /= (i + 1);
}
return res;
}
// Driver program
int main()
{
int n = 7;
printPascal(n);
return 0;
}