java设计一个方法Combination(),给定两个非负整数m, n(m>n),计算C_n^m的值
时间: 2023-12-10 18:42:25 浏览: 40
可以使用递归来实现组合公式:C_n^m = C_(n-1)^(m-1) + C_(n-1)^m
Java代码如下:
```java
public class Combination {
public static void main(String[] args) {
int n = 5;
int m = 3;
int result = combination(n, m);
System.out.println("C_" + n + "^" + m + " = " + result);
}
public static int combination(int n, int m) {
if (m == 0 || m == n) {
return 1;
} else {
return combination(n - 1, m - 1) + combination(n - 1, m);
}
}
}
```
输出结果为:C_5^3 = 10
相关问题
用java设计一个方法Combination(),给定两个非负整数m, n(m>n),计算C_n^m的值
好的,我可以帮你设计这个方法。首先,我们需要知道组合数的计算公式:
C_n^m = n! / (m! * (n-m)!)
其中,n! 表示 n 的阶乘,即 n*(n-1)*...*2*1。
那么,我们可以用递归的方式来计算阶乘和组合数,具体实现如下:
```java
public class Combination {
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static int combination(int m, int n) {
if (m == n) {
return 1;
} else {
return factorial(n) / (factorial(m) * factorial(n - m));
}
}
public static void main(String[] args) {
int m = 5;
int n = 10;
int result = combination(m, n);
System.out.println("C_" + m + "^" + n + " = " + result);
}
}
```
在上面的代码中,我们定义了两个方法:factorial() 和 combination()。factorial() 方法用来计算阶乘,而 combination() 方法则用来计算组合数。
最后,在 main() 方法中,我们给定了 m=5 和 n=10 的值作为示例,然后调用 combination() 方法计算 C_5^10 的值,并将结果打印出来。
希望这个代码对你有所帮助!
用java设计一个方法Combination(),给定两个非负整数m, n(m>n),计算C_n^m的值,导入factorial
好的,如果你已经有了计算阶乘的方法 `factorial()`,那么可以在计算组合数的方法 `Combination()` 中调用 `factorial()` 方法来计算阶乘,具体实现如下:
```java
public class Combination {
public static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
} else {
return n * factorial(n - 1);
}
}
public static int Combination(int m, int n) {
if (m == n) {
return 1;
} else {
return factorial(n) / (factorial(m) * factorial(n - m));
}
}
public static void main(String[] args) {
int m = 5;
int n = 10;
int result = Combination(m, n);
System.out.println("C_" + m + "^" + n + " = " + result);
}
}
```
在上面的代码中,我们定义了两个方法:`factorial()` 用来计算阶乘,`Combination()` 用来计算组合数。在 `Combination()` 方法中,我们调用了 `factorial()` 方法来计算阶乘。
最后,在 `main()` 方法中,我们给定了 m=5 和 n=10 的值作为示例,然后调用 `Combination()` 方法计算 C_5^10 的值,并将结果打印出来。
希望这个代码对你有所帮助!