Calculate General Term in Java (Binomial Theorem)

Calculating General Term in Binomial Theorem 2 term expansion in Java
This illustrates calculating the general term in a bionomial expansion (x+a)^n using the standard bionomial theorem formula for calculating the general term.

The forumla used is ((nCr)*(x^(n-r))*(a^r))






import java.util.*;
class GeneralTerm
{
    public static void main(String args[])
    {
   
    // Create Scanner object
    Scanner s=new Scanner(System.in);

   
    System.out.println("Enter the values of x,a,n in (x+a)^n");

    // Take values of x,a,n respectively
    int x=s.nextInt();
    int a=s.nextInt();
    int n=s.nextInt();

    System.out.println("Enter the value of r to find general term");

    // Take the value of r
    int r=s.nextInt();


    // To calculate nCr  
    long nCr=calculatenCr(n,r);

      
        // nCr is -1 when n<r
        if(nCr!=-1)
        {
            // Calculate x^(n-r)
            double y=Math.pow((double)x,(double)n-r);

            // Calculate a^r
            double z=Math.pow((double)a,(double)r);

            // Calculate and Print general term ((nCr)*(x^(n-r))*(a^r))
            System.out.println("The result is "+nCr*y*z);
        }      
   
    }


    // Method to calculate nCr
    public static long calculatenCr(int n,int r)
    {

    long res=1;

        if(n>=r)
        {
            res=getFact(n)/(getFact(n-r)*getFact(r));
            return res;
        }
        else return -1;

    }

    public static long getFact(int n)
    {
        long f=1;

        for(int i=n;i>=1;i--)
        {
        f*=i;
        }

    return f;
    }

}

Sample Output


Enter the values of x,a,n in (x+a)^n
5
4
2
Enter the value of r to find general term
2
The result is 16.0


Analysis

nCr=-1: -1 is returned if n<r which is absurd.
nCr!=-1: If n>r then nCr is not equal to -1.
Math.pow((double)x,(double)n-r): This (pow) is a method of java.lang.Math class which takes two double values and find the power. The first parameter is the number and the second one is the power. As x and n-r are long values, they are typecasted into double. This method returns a double value which is the required result. Therefore, x^(n-r) [x to the power n-r] is calculated. Similarily, a^r (a power r) is also calculated.
The General Term:  The general term formula is ((nCr)*(x^(n-r))*(a^r)). The general term is also called as rth term.
Calculating combination: This is discussed in finding number of combinations in Java
Factorial: This is discussed in finding factorial of a number in Java post.

In this way we can calculate the general term in binomial theorem in Java.

No comments: