Skip to content

Instantly share code, notes, and snippets.

@timgianitsos
Last active April 8, 2022 07:36
Show Gist options
  • Save timgianitsos/1ab7770c82495048cdd1ae39cbedf296 to your computer and use it in GitHub Desktop.
Save timgianitsos/1ab7770c82495048cdd1ae39cbedf296 to your computer and use it in GitHub Desktop.
import java.math.BigInteger;
import java.util.Scanner;
/*
To run, use
`javac *.java && java -ea BinomialCoefficients`
Author: Tim Gianitsos
*/
public class BinomialCoefficients
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Binomial Expansion. Enter parameters for an expression of the"
+ " form (ax + by)^c");
System.out.println("Enter the value of \"c\", the exponent: ");
int exponent = scan.nextInt();
while (exponent < 0)
{
System.out.println("You must enter a number greater than or equal to 0. Try again: ");
exponent = scan.nextInt();
}
System.out.println("Enter the value of \"a\", the coefficient of the first term");
int firstCoef = scan.nextInt();
System.out.println("Enter the value of \"b\", the coefficient of the second term");
int secondCoef = scan.nextInt();
System.out.println("Calculating (" + firstCoef + "x + " + secondCoef + "y)^" + exponent);
calculatePolynomial(exponent, firstCoef, secondCoef);
scan.close();
}
private static void calculatePolynomial(int exponent, int firstCoef, int secondCoef)
{
if (exponent == 0)
{
System.out.println("Result: 1");
}
else
{
BigInteger fc = BigInteger.valueOf(firstCoef);
BigInteger sc = BigInteger.valueOf(secondCoef);
System.out.print("Result: " + fc.pow(exponent) + " x^" + exponent);
for (int i = 1; i < exponent; i++)
{
System.out.print(" + " +
nCr(exponent, i).multiply(fc.pow(exponent - i)).multiply(sc.pow(i))
+ " x^" + (exponent - i) + " y^" + i);
}
System.out.println(" + " + sc.pow(exponent) + " y^" + exponent);
}
}
private static BigInteger nCr(int n, int r)
{
BigInteger result = new BigInteger("1");
int nMinusr = n - r;
if (r >= n / 2)
{
for (; n > r; n--)
result = result.multiply(BigInteger.valueOf(n));
for (; nMinusr > 1; nMinusr--)
result = result.divide(BigInteger.valueOf(nMinusr));
}
else
{
for (; n > nMinusr; n--)
result = result.multiply(BigInteger.valueOf(n));
for (; r > 1; r--)
result = result.divide(BigInteger.valueOf(r));
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment