Printing Pascals Triangle (recursive) (JAVA)

爱⌒轻易说出口 提交于 2019-12-11 06:24:52

问题


So far I have this, but I am not quite sure how printPTriangle can print the triangle using the code. If someone could help me out with this, I would be grateful.

public static int factorial(int n) {
    if (n == 1) {
        return 1;
    }
    return n * (factorial(n - 1));
}

public static int pascalsNumber(int x, int y) {
    return factorial(x)/(factorial(y) * factorial((x - y))); //Using combinations formula
}

public static void printPTriangle(int z) {



}

回答1:


Try this,

public class PascalTriangle {

public static void main(String[] args) {

    int rows = 10;


    for(int i =0;i<rows;i++) {
        int number = 1;
        System.out.format("%"+(rows-i)*2+"s","");
        for(int j=0;j<=i;j++) {
             System.out.format("%4d",number);
             number = number * (i - j) / (j + 1);

        }
        System.out.println();
    }

}
}

Note the formatting commands used above to create a nicely formatted triangle. %4d instructs the formatter to print the number within 4 spaces.




回答2:


I too am a beginner at Java and am working on Pascals triangle. I liked the formatting indicated above and introduced it to my code. I made the spacing a little larger to account for a bigger triangle.

import java.util.Scanner;

public class Pascal {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the row number up to which Pascal's triangle has to be printed: ");
        int row = scanner.nextInt();
        print(row);

        scanner.close();
    }

    public static void print(int n) {
        for (int i = 0; i < n; i++) {
            System.out.format("%"+(n-i)*3+"s","");
            for (int j = 0; j <= i; j++) {
                System.out.format("%6d",(pascal(i, j)));
            }
            System.out.println();
        }
    }

    public static int pascal(int i, int j) {
        if (j == 0) {
            return 1;
        } else if (j == i) {
            return 1;
        } else {
            return pascal(i - 1, j - 1) + pascal(i - 1, j);
        }

    }

}



回答3:


Here is the solution:

public static void main(String[] args) 
{
    pascal(1,10);
}
static int pascal(int start, int end)
{
    if(start>=end)
        return 0;
    int number = 1;
    System.out.format("%"+(end-start)*2+"s","");
    pascal2(start,number,0);
    System.out.println();
    return pascal(start+1,end);
}
static int pascal2(int start,int number,int end)
{
    if(end>start)
        return 1;
    System.out.format("%4d",number);
    return pascal2(start,number * (start - end) / (end + 1),end+1);
}


来源:https://stackoverflow.com/questions/26749516/printing-pascals-triangle-recursive-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!