Guest User

Program to Find the Terms of an Expansion

a guest
Oct 29th, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.46 KB | None | 0 0
  1. /**
  2.  * Just a random program for 'Binomial Theorem' (Class-XI Maths).
  3.  */
  4. import java.util.*;
  5. public class Binomial_Theorem
  6. {
  7.     static long fact(int num) //Function to find factorial of a number.
  8.     {
  9.         int i;
  10.         long f=1;
  11.         for(i=1;i<=num;i++)
  12.         {
  13.             f *= i;
  14.         }
  15.        
  16.         return f;
  17.     }
  18.    
  19.     static long combination(int n, int r) //Function to find the combination required for a term.
  20.     {
  21.         long comb = fact(n) / (fact(n-r)*fact(r));
  22.         return comb;
  23.     }
  24.    
  25.     static void findExpansion(char a, char b, int power) //Function to find the terms of an expansion.
  26.     {
  27.         int i;
  28.         String aterm = "";
  29.         String bterm = "";
  30.         String term;
  31.         long ncr; String ncrterm = "";
  32.         for(i=0;i<=power;i++)
  33.         {
  34.             ncr = combination(power, i);
  35.             ncrterm = Long.toString(ncr); //nCr.
  36.             aterm = Character.toString(a) + "^" + Integer.toString(power - i); //a^n-r
  37.             bterm = Character.toString(b) + "^" + Integer.toString(i); //b^r
  38.             term = ncrterm + " * " + aterm + " * " + bterm;
  39.             System.out.println("Term "+(i+1)+" = "+term);
  40.         }
  41.     }
  42.    
  43.     public static void main(String[] args)
  44.     {
  45.         Scanner sc = new Scanner(System.in);
  46.        
  47.         System.out.println("Please enter the first variable in (a+b)^n.");
  48.         char a = sc.next().charAt(0);
  49.        
  50.         System.out.println("Please enter the second variable in (a+b)^n.");
  51.         char b = sc.next().charAt(0);
  52.        
  53.         System.out.println("Please enter 'n' in (a+b)^n.");
  54.         int power = sc.nextInt();
  55.        
  56.         findExpansion(a, b, power);
  57.        
  58.         sc.close();
  59.     }
  60. }
Add Comment
Please, Sign In to add comment