java - NchooseR Java 递归程序
问题描述
当用户输入两个数字时,我在查找“NChooseR”值时遇到问题,并且程序必须使用递归。"NchooseR" 公式必须是n! / r!(n-r)!
Scanner input = new Scanner(System.in);
System.out.println("This program will calculate the number of ways to chose r different objects from a set of n objects\n");
System.out.println("How many objects would you like to chose? (r value)");
int userR = input.nextInt();
System.out.println("How many objects are there to chose from? (n value)");
int userN = input.nextInt();
System.out.println("There are " + nchooser(userN, userR) + " ways to chose " + userR + " objects from a set of " + userN + " objects");
}
public static long factorialn(int n) {
//return a value of one for terms one and two
if ((n == 1) || (n == 2)) {
return 1;
} else {
return factorialn(n - 1) + factorialn(n - 2);
}
}
public static long factorialr(int r) {
//return a value of one for terms one and two
if ((r == 1) || (r == 2)) {
return 1;
} else {
return factorialr(r - 1) + factorialr(r - 2);
}
}
public static long factorialnr(int r, int n) {
//return a value of one for terms one and two
if ((r == 1) || (r == 2) || (n == 1) || (n == 2)) {
return 1;
} else {
return factorialr((n-r) - 1) + factorialr((n - r) - 2);
}
}
public static long nchooser(int r, int n) {
return factorialn(n) / (factorialr(r) * (factorialnr(n,r)));
}
解决方案
这是一些可能适用于更大数字的代码:
public static final long f(final int n) { // factorial
long i,p;
if(n<=1)
p=1;
else for(p=n,i=2;i<=n-1;i++)
p=p*i;
return (p);
}
public static final long c(final int n,final int r) { // binomial coefficient
long i,p;
if(r<0||n<0||r>n)
p=0;
else if(r==0)
p=1;
else if(r>n-r)
p=c(n,n-r);
else {
for(p=1,i=n;i>=n-r+1;i--)
p=p*i;
p=p/f(r);
}
return p;
}
推荐阅读
- swift - 为什么这个函数没有返回任何东西?
- php - 如何在同一页面中使用 html 和 php 在下拉的选择更改事件的输入字段中从数据库中获取选定的数据
- arrays - 使用 mongodb 的 java 驱动程序从集合中获取数组字段
- c# - .Net Core 2 OpenID Connect 身份验证和多个身份
- google-cloud-platform - Apache Beam python sdk 因 IllegalArgumentException 而失败
- google-drive-api - 使用 Drive API 使用 Word 打开 Google Drive 文件
- yii2-advanced-app - 例外:LINUX下的Unknown Property,但在使用kartik widget CheckBoxX的Windows下没有
- swift - 尝试将图像上传到 Firebase 存储和数据库时出现问题?
- php - 检查 SSL 证书 Php Fopen 和 Curl
- ios - 主从应用程序中 UITableViewCell 的 Peek&Pop