In: Computer Science
write a program named Combinations.java that gets user input for two integers n and k, then computes and displays the value of n choose k using the efficient method of equation. you may assume that the user's input makes sense (i.e, n and k are non negative, and n is at least k). your code should work for any reasonably small non- negative values of n and k, including zero.
//Combinations.java
import java.util.Scanner;
public class Combinations {
    
    // Calculating factorial of n
    public static int factorial(int n)
    {
        int result = 1;
        if (n < 0) {
            return 0;
        }
        while (n > 1) {
            result *= n;
            n--;
        }
        return result;
    }
    // Calculating n choose k
    public static int combinations(int n, int k){
        if(n>=0 && k>=0)
            return factorial(n)/(factorial(n-k)*factorial(k));
        else
            return -1;
    }
    // main method
    public static void main(String args[]) {
        Scanner scanner = new Scanner(System.in);
        
        // Reading input
        System.out.print("Please enter a value for n: ");
        int n = scanner.nextInt();
        System.out.print("Enter k: ");
        int k = scanner.nextInt();
        
        // Making call to combinations function
        int result = combinations(n,k);
        
        // Printing output
        if(result==-1){
            System.out.println("Error: Invalid input. Both n and k should be positive");
        }
        else{
            System.out.println("Result: "+result);
        }
    }
}


