Search code examples
javaarrayscombinationspascals-triangle

Best way to generate pascal's triangle (of two mentioned ways)


I have an programming assignment in Java.

I have implemented it by making an nCr ( http://en.wikipedia.org/wiki/Combination ) function then using a double for loop to make the triangle by printing it out.

However, the assignment calls for a uneven 2d array to be created and then populated by adding the two numbers from the previous lines and then printing the array out.

I know I am going to have to do the assignment the way it asks, however I have a small feeling that (at least for small triangles anyway) that the approach I have implemented is better.

Which is the better approach?


Solution

  • I'd think the method called for by the assignment would be better. You're method requires a number of multiplications to calculate each of the elements of the triangle. This number will increase for each row of the triangle you need to calculate.

    The assignment's method, however, requires a single addition for each element of the triangle.