在C语言中,有多种方法可以用来计算组合数。以下是几种常见的方法:
方法一:迭代法
```c
include
int combination(int n, int m) {
int result = 1;
if (m > n / 2) m = n - m;
for (int i = n, j = 1; i >= n - m + 1; i--, j++) {
result *= i;
result /= j;
}
return result;
}
int main() {
int n, m;
printf("请输入组合数中的n和m(m <= n):\n");
scanf("%d %d", &n, &m);
printf("C(%d, %d) = %d\n", n, m, combination(n, m));
return 0;
}
```
方法二:递归法
```c
include
int sum(int m, int n) {
if (n == m || n == 0)
return 1;
else
return sum(m - 1, n) + sum(m - 1, n - 1);
}
int main() {
int m, n;
printf("请输入组合数中的m和n(m <= n):\n");
scanf("%d %d", &m, &n);
printf("C(%d, %d) = %d\n", m, n, sum(m, n));
return 0;
}
```
方法三:阶乘法
```c
include
unsigned long long factorial(int x) {
unsigned long long s = 1;
for (int i = 1; i <= x; i++)
s *= i;
return s;
}
int combination(int m, int k) {
return factorial(m) / (factorial(k) * factorial(m - k));
}
int main() {
int m, k;
printf("请输入组合数中的m和k(10 >= m >= k > 0):\n");
scanf("%d %d", &m, &k);
printf("C(%d, %d) = %llu\n", m, k, combination(m, k));
return 0;
}
```
方法四:循环法
```c
include
int combination(int n, int m) {
int result = 1;
for (int i = 1; i <= m; i++) {
result *= (n - i + 1);
result /= i;
}
return result;
}
int main() {
int n, m;
printf("请输入组合数中的n和m(m <= n):\n");
scanf("%d %d", &n, &m);
printf("C(%d, %d) = %d\n", n, m, combination(n, m));
return 0;
}
```
方法五:避免溢出
```c
include
long long factorial(int x) {
long long s = 1;
for (int i = 1; i <= x; i++)
s *= i;
return s;
}
int combination(int m, int k) {
if (k > m - k)
k = m - k;
long long result = 1;
for (int i = 1; i <= k; i++) {
result = result * (m - i + 1);
result = result / i;
}
return (int)result;
}
int main() {
int m, k;
printf("请输入组合数中的m和k(10 >= m >= k > 0):\n");
scanf("%d %d", &m, &k);
printf("C(%d, %d) = %lld\n", m, k, combination(m, k));
return 0;
}
```
这些方法各有优缺点,可以根据具体需求和计算量选择合适的方法。迭代法和循环法在计算组合数时效率较高,而递归法和阶