Compute nCr = n!/(r!(n-r)!)
In this step, you will implement a function to calculate the factorial and compute combinations using the formula nCr = n! / (r! * (n-r)!).
Open the previous combinations.c
file and update it with the factorial and combination calculation functions:
cd ~/project
nano combinations.c
Add the following code to implement factorial and combination calculations:
#include <stdio.h>
// Function to calculate factorial
unsigned long long factorial(int num) {
if (num == 0 || num == 1) {
return 1;
}
unsigned long long result = 1;
for (int i = 2; i <= num; i++) {
result *= i;
}
return result;
}
// Function to calculate combinations (nCr)
unsigned long long combinations(int n, int r) {
// Validate input
if (r > n) {
return 0;
}
// Use the combination formula: nCr = n! / (r! * (n-r)!)
unsigned long long numerator = factorial(n);
unsigned long long denominator = factorial(r) * factorial(n - r);
return numerator / denominator;
}
int main() {
int n, r;
// Prompt user to enter values for n and r
printf("Enter the value of n: ");
scanf("%d", &n);
printf("Enter the value of r: ");
scanf("%d", &r);
// Calculate and print the combination
unsigned long long result = combinations(n, r);
printf("Combination C(%d, %d) = %llu\n", n, r, result);
return 0;
}
Compile and run the program:
gcc combinations.c -o combinations
./combinations
Example output:
Enter the value of n: 5
Enter the value of r: 3
Combination C(5, 3) = 10
Key points in this implementation:
factorial()
function calculates the factorial of a given number
combinations()
function implements the combination formula
- Uses
unsigned long long
to handle larger factorial calculations
- Validates input to prevent invalid combinations