Question:
Program to calculate binomial coefficient and output pascal's triangle without arrays?
Yash
2012-10-17 17:07:51 UTC
Hi everyone!

I need to write a program with a method named "choose" to compute the binomial coefficient c(n,k) after the user enters n & k. I then need to have second part of the program where the program asks the user to input an integer n and then the program prints the first n rows of Pascal's triangle. On the ith row, the jth number is C(i, j). Both i and j start from 0. I am having a lot of trouble with this program so if somebody could show me how to do this it would be much appreciated! Here is what I have so far...i know it's not correct though.

import java.util.Scanner;
public class choose2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter values for n and k: ");
double i = input.nextInt();
double j = input.nextInt();
System.out.print("The binomial coefficient is: " + choose(i, j));


}

public static double choose(double n, double k) {
double dividend = 1;
double divisor = 1;
int x = 1;
x = x + 1;
for (n = 0; n <= (n-(k-1)); n++)
dividend = n * (n-x);
for (k = 0; k == 1; k++)
divisor = k * (k - x);

return dividend/divisor;

}

}
Three answers:
modulo_function
2012-10-17 17:44:56 UTC
Your choose method is faulty.



0! is defined to be 1.



I'd recommend rewriting that method to invoke another method to get the factorials and do the calculation.



public static int choose( int n, int k ) { // factorials and binomial coefficients are ints

...return fact(n)/fact(n-k)/fact(k);

}



Now write the fact(int n) method to return factorial:



public static int fact( int n ) {

...if( n==0 ) return 1;

...return n*fact(n-1);

}



Oops, I did the program for you, please forgive me...
Erika
2016-07-28 22:46:48 UTC
We are able to to find the coefficients utilising pascal's triangle 1 (a+b)zero 1 1 (a+b)1 1 2 1 (a+b)2 1 three three 1 (a+b)three 1 four 6 4 1 (a+b)4 the first & last coefficients of a ramification is 1. In pascal's triangle for eg the 2nd coefficient of (a+b)3 is bought by way of add 1+2=3 & third coefficient also through including 2+1=three the 2nd coefficient of (a+b)four is obtained by using including 1+3=4& the rd coeff by addding three&three , the 4th coefficient by including 3&1 similarly u can in finding the coeff of alternative expansion also
anonymous
2014-06-21 05:21:33 UTC
The binomial coefficient C(n,k) can be recursively computed as


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...