Pascal's Triangle : Awesome Code


For the newbies, who don't know what a pascal's triangle is, here is a small explanation to guide you.

Pascal's triangle is a triangular array of the binomial coefficients in a triangle. It is named after the French mathematician Blaise Pascal in much of the Western world, although other mathematicians studied it centuries before him in Greece, India, Persia, China, and Italy.

Pascal's Triangle

The rows of Pascal's triangle are conventionally enumerated starting with row n = 0 at the top. The entries in each row are numbered from the left beginning with k = 0 and are usually staggered relative to the numbers in the adjacent rows. A simple construction of the triangle proceeds in the following manner. On row 0, write only the number 1. Then, to construct the elements of following rows, add the number directly above and to the left with the number directly above and to the right to find the new value. If either the number to the right or left is not present, substitute a zero in its place. For example, the first number in the first row is 0 + 1 = 1, whereas the numbers 1 and 3 in the third row are added to produce the number 4 in the fourth row.

Just when I was going through some programming codes for this Pascal's triangle, I found one which was really amazing. No multi-dimension arrays, no space compexity and minimal time complexity.


#include <iostream>
using namespace std;
int main()
{
    int n,k,i,x;
    cout << "Enter a row number for Pascal's Triangle: ";
    cin >> n;
    for(i=0;i<=n;i++)
    {
        x=1;
        for(k=0;k<=i;k++)
        {      
            cout << x << "   ";
            x = x * (i - k) / (k + 1);
        }
        cout << endl;
    }
    return 0;
}


Hats off to the programmer who came up with this code !!

Comments

  1. sooo it should be 210 at the bottom, not 200

    ReplyDelete
  2. yes hannah.. you are right.. it should be 210..

    ReplyDelete
  3. You're right, it should be 210 not 200. I was misled doing some probability calculations on dice-rolls using this erroneous table! I was beating myself up but my complicated 15-term equation was sound, it was the TABLE trying to get the value C(10,4) that was wrong, hahaha!

    ReplyDelete
  4. Rather than C++, shouldn't this code be written in... Pascal? (A programming language that I was taught in Uni in 1984)

    ReplyDelete

Post a Comment

Popular Posts