nCr in Java

This commit is contained in:
newt 2024-10-09 18:02:37 +01:00
parent 48382715b3
commit d2a18f7764
7 changed files with 52 additions and 12 deletions

1
.gitignore vendored
View file

@ -2,3 +2,4 @@
venv
private
__pycache__
*.out

3
.vscode/settings.json vendored Normal file
View file

@ -0,0 +1,3 @@
{
"java.project.sourcePaths": ["java"]
}

View file

View file

@ -0,0 +1,9 @@
int factorial(int n) {
int ans = 1;
for (int i = 2; i <= n; i++) {
ans *= i;
}
return ans;
}

View file

@ -1,14 +1,5 @@
#include <stdio.h>
int factorial(int n) {
int ans = 1;
for (int i = 2; i <= n; i++) {
ans *= i;
}
return ans;
}
#include "helpers/factorial.c"
int nCr(int n, int r) {
return factorial(n) / factorial(r) * factorial(n - r);

35
java/calculators/ncr.java Normal file
View file

@ -0,0 +1,35 @@
package calculators;
import java.util.Scanner;
class CombinationCalculator {
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));
}
public static void main(String[] args) {
// Open a scanner and take the relevant inputs
Scanner scan = new Scanner(System.in);
System.out.print("Please input the value for n: ");
int n = scan.nextInt();
System.out.print("Please input the value for r: ");
int r = scan.nextInt();
// Close the scanner, and calculate the result
scan.close();
int result = nCr(n, r);
System.out.println(result);
}
}

View file

@ -7,8 +7,9 @@
### Table of contents
- [Python](python)
- [C](c)
- [Python](languages/python)
- [C](languages/c)
- [Java](languages/java)
- [Project Euler](euler)
- [GCSE Computer Science](school/gcse)
- [Royal Institute Computer Science Masterclass 2021](school/royal%20institute)