the-honk/java/calculators/ncr.java

48 lines
928 B
Java
Raw Normal View History

2024-10-09 17:02:37 +00:00
package calculators;
2024-10-09 17:02:37 +00:00
import java.util.InputMismatchException;
2024-10-09 17:02:37 +00:00
import java.util.Scanner;
class CombinationCalculator {
2024-10-09 17:02:37 +00:00
private static Scanner scanner = new Scanner(System.in);
2024-10-09 17:02:37 +00:00
private static int factorial(int n) {
int res = 1;
for (int i = 2; i <= n; i++) {
res *= i;
}
return res;
}
private static int nCr(int n, int r) {
return factorial(n) / (factorial(r) * factorial(n - r));
}
2024-10-09 17:02:37 +00:00
private static int intInput(String message) {
int value = -1;
2024-10-09 17:02:37 +00:00
2024-10-09 17:02:37 +00:00
while (value < 0) {
try {
System.out.print(message);
value = scanner.nextInt();
} catch (InputMismatchException e) {
scanner.next();
}
}
2024-10-09 17:02:37 +00:00
2024-10-09 17:02:37 +00:00
return value;
}
2024-10-09 17:02:37 +00:00
2024-10-09 17:02:37 +00:00
public static void main(String[] args) {
// Take inputs
int n = intInput("Please input the value for n: ");
int r = intInput("Please input the value for r: ");
scanner.close();
2024-10-09 17:02:37 +00:00
2024-10-09 17:02:37 +00:00
// Calculate the result
2024-10-09 17:02:37 +00:00
int result = nCr(n, r);
System.out.println(result);
}
}