Programming Geek
Rated 4.7/5 based on 1446 reviews

Pascal Triangle


The Pascal triangle problem can be understood by the following visualization:



Each row of a pascal triangle can be viewed as the coefficients of the expansion of (x + y)n  .

The following program prints the pascal triangle separated by space with O(n*n) complexity .


import java.math.*;

public class Solution {

    public static void main(String[] args) {
      
        printPascal(Integer.parseInt(args[0]));
    }
    static void printPascal(int n)
{
  for (int line = 1; line <= n; line++)
  {
    BigInteger b=BigInteger.valueOf(1); 
    for (int i = 1; i <= line; i++)  
    {
      System.out.print(b+" ");  
      b = b.multiply(BigInteger.valueOf(line - i));
      b=b.divide(BigInteger.valueOf(i));    
          
    }
    System.out.println();
  }
}
}

No comments :

Post a Comment