Labels

Monday, February 15, 2016

A java program to calculate combinations of r objects from a set of n objects

A java program to calculate combinations of r objects from a set of n objects;

import java.util.Scanner;
class Recursion{
    double c,n;
    double A (double n){
       if (n==1)
           return 1;
       c=A(n-1)*n;
       return c;
    }
    double B1(double r)
    {
        if(r==1)
           return 1;
        n=B1(r-1)*r;
        return n;
    }
    double B2(double d)
    {
        double r;
        if(d==1)
            return 1;
        r=B2(d-1)*d;
        return r;
    }
}
public class comb {
    public static void main(String[] args)
    {
        Scanner s=new Scanner(System.in);
        System.out.print("Enter the highest power of combination: ");
        double n= s.nextDouble();
        System.out.print("Enter the power till which user wants answer: ");
        double r= s.nextDouble();
        Recursion rec=new Recursion();
        double a,b,diff;
        diff=n-r;
        a= rec.A(n);
        b= rec.B1(r)*rec.B2(diff);
        double result= a/b;
        System.out.println("Result: "+result);
    }
}

To run source code follow following steps:-
  • Save file with name comb.java
  • Open terminal or cmd and move to file location
  • Type: javac comb.java
  • Type: java comb

No comments:

Post a Comment