Search code examples
javarecursionpascals-triangle

Pascal's triangle code failing after certain row


import java.util.*;
public class PascalFinal
{
public static void main() 
{
    Scanner f = new Scanner(System.in);
    System.out.print("How many rows of Pascal's triangle do you want to print: ");
    int row = f.nextInt();
    Pascal(row);

    showPascal(Pascal(row));
}

public static void showPascal(int[][] Pascal)
{
    for(int a = 0; a < Pascal.length; a++)
    {
        for(int b = 0; b < Pascal[a].length; b++)
        {
            System.out.print(Pascal[a][b] + " ");
        }
        System.out.println();
    }
}

public static int[][] Pascal(int x)
{
    int[][] Pascal = new int[x][];
    int rowLength = 1;
    for(int a = 0; a < x; a++)
    {
        Pascal[a] = new int[rowLength];
        rowLength++;
    }



    for(int a = 0; a < Pascal.length; a++)
    {
        for(int b = 0; b < Pascal[a].length; b++)
        {
            int Piscal = a-b;

            Pascal[a][b] = Factorial(a)/Factorial(b)/Factorial(Piscal);
        }
    }

    return Pascal;
}

public static int Factorial(int n)
{

    if (n < 0) 
    {
        int x = -1;
        return x;
    }

    if (n == 0) 
    {
        int x = 1;
        return x;
    }
    else 
    {
        return (n * Factorial(n - 1));
    } 
}

When I run that code, it works perfectly fine for the first 13 lines, however it then starts putting in weird values for the rest of the rows. My first though was that it could be due to the values getting too big from the factorial method and the int datatype not being able to hold it but I am not sure. No clue why this is getting messed up. Please help.

Edit: I tried using the long datatype instead of int, but the same issue occurs once I get past 20 rows.


Solution

  • If the Pascal's triangle that you have to draw is the one designed here you do not need to evaluate any factorial.

    Each row can be evaluated using the previous row with simple sums...

    You can do it using an array. As a suggestion, start with the arrary: [0, 1, 0] and remember that the next row can be evaluated doing a sum of the adjacent numbers of the previous row.

    You need to loop over [0, 1, 0] and create [0,1,1,0] and then [0,1,2,1,0]

    As you can see, the first is 0 and remains always 0, the next is the sum of the first two, and so on...