gpt4 book ai didi

java - NChooseR Java 递归程序

转载 作者:行者123 更新时间:2023-11-30 12:06:45 25 4
gpt4 key购买 nike

当用户输入两个数字时,我在查找“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;
}

关于java - NChooseR Java 递归程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55349192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com