Search code examples
javaalgorithmrecursionpascals-triangle

Why my Pascal's triangle code doesn't work?


I have been trying to write Pascal's triangle using a combination formula but it just doesn't work properly and I am not sure what the problem is?

Here's the input:

public class Probs {
    public static int fact(int n) {
        int f;
        for (f = 1; n > 1; n--) {
            f *= n;
        }
        return f;
    }

    public static int comb(int i, int j) {
        return fact(i) / fact(i - j) * fact(j);
    }

    public static void main(String[] args) {
        int n = 5;
        int i;
        int j;
        for (i = 0; i < n; i++) {
            for (j = 0; j < n - i; j++) {
                System.out.print(" ");
            }
            for (j = 0; j <= i; j++) {
                System.out.print(" " + comb(i, j));
            }
            System.out.println();
        }
    }
}

The Output:

    1
   1 1
  1 2 4
 1 3 12 36
1 4 24 144 576

Can you explain me why in a beginner-friendly way?


Solution

  • You need to add parentheses around the operations in comb() to get the correct precedence.

    Both / and * have the same precedence, so when you write

    return fact(i)/ fact(i-j)*fact(j);
    

    This expression is actually equivalent to

    return (fact(i)/fact(i-j)) * fact(j);
    

    Which is not really what you want...

    Fix it by adding parentheses around the product in the denominator:

    return fact(i) / (fact(i-j)*fact(j));