Search code examples
javapascals-triangle

How to solve Pascal triangle loop fails issue?


I'm facing an error on my Pascal triangle, but I don't know whether it's Java or my code which is the problem. Here is the code:

import java.util.Scanner;

public class sdz {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int levels;
        levels = sc.nextInt();

        for(int i = 0; i <= levels; i++){
            for(int j =0; j <= i; j++){
                System.out.print(combinatorial(i,j) + " ");
            }

            System.out.println();

        }
    }
    static int fact(int n ){
        if(n > 0)
            return n * fact(n-1);
        else
            return 1;
    }

    static int combinatorial(int n , int r){

        return fact(n)/(fact(r) * fact(n-r));
    }

}

When I input the level to 13, it fails. Here is the result:

The loop at 13


Solution

  • This is caused by integer overflow issue. The result of fact(13) is 6227020800, which is larger than what fits in an integer.

    Either use long (which would only delay the issue), BigInteger or define a combinatorial object. And use dynamic programming principles to avoid repetitive calculation, as shown by @Kaidul