| import java.util.Scanner; |
| |
| class Proj3 |
| { |
| public static void main(String[] args) |
| { |
| Scanner s = new Scanner(System.in); |
| |
| System.out.print("Enter a positive integer bound: "); |
| int num = Integer.parseInt(s.nextLine()); |
| System.out.println("Pascal's Triangle:\n"); |
| |
| // Start iterating through numbers of Pascal's Triangle |
| for (int i = 0; i <= num; i++) |
| { |
| // In order to make table look good, calculate the |
| // spacing needed to center it. |
| for (int space = num - i; space > 0; space--) |
| { |
| System.out.print(" "); |
| } |
| |
| for (int j = 0; j <= i; j++) |
| { |
| int value = getFactorial(i) / (getFactorial(j) * getFactorial(i - j)); |
| |
| // If value is greater than 1 digit, then only add 1 space, otherwise add 2 |
| if(Integer.toString(value).length() == 1) |
| System.out.print(" "); |
| else |
| System.out.print(" "); |
| |
| System.out.print(value); |
| |
| // If value is greater than 2 digits, do not add a space after |
| if(Integer.toString(value).length() < 3) |
| System.out.print(" "); |
| } |
| System.out.println(); |
| } |
| |
| // Iteration for Binomial Expansions |
| System.out.println("\nBinomial Expansions:\n"); |
| |
| // Always output for expansion by default |
| System.out.println("(x + y)^0 = 1"); |
| for (int i = 1; i <= num; i++) |
| { |
| int x = i; |
| System.out.print("(x + y)^" + i + " = "); |
| for (int j = 0; j <= i; j++) |
| { |
| int coef = getFactorial(i) / (getFactorial(j) * getFactorial(i - j)); |
| |
| if(j != 0) |
| System.out.print(" + "); |
| |
| if (coef > 1) |
| System.out.print(coef); |
| |
| if (x > 1) |
| System.out.print("x^" + x); |
| else if (x == 1) |
| System.out.print("x"); |
| |
| if (j > 1) |
| System.out.print("y^" + j); |
| else if (j == 1) |
| System.out.print("y"); |
| |
| x--; |
| } |
| System.out.println(); |
| } |
| } |
| |
| private static int getFactorial(int num) |
| { |
| if(num == 0) |
| return 1; |
| |
| int returnval = num; |
| |
| for (int i = num - 1; i > 0; i--) |
| returnval *= i; |
| |
| return returnval; |
| } |
| } |