我是 Java 的新手,但当然想变得更好。我无法解决一个看起来很简单的问题,但它就是:编写一个计算 n!/k! 的程序。 (阶乘),将 n 和 k 作为用户输入,检查是否 n>k>0,如果不是则打印错误。
这是我目前所拥有的。我知道我还没有完成问题的错误部分,但我想让它现在起作用。计算一个阶乘非常简单,但将两者相除似乎是一个挑战。任何帮助,将不胜感激!提前致谢!
import java.util.Scanner;
public class nkFactorial {
@SuppressWarnings({ "resource" })
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter n");
int n = input.nextInt();
System.out.println("Enter k");
int k = input.nextInt();
long nfactorial=1;
long kfactorial=1;
do {
nfactorial *=n;
n--;
kfactorial *=k;
k--;
} while (n>k && k>1);
System.out.println("n!/k!=" + nfactorial/kfactorial );
}
}
最佳答案
试试这个:
static int divFactorials (int n, int k) {
int result = 1;
for (int i = n; i > k; i--)
{
result *= i;
}
return result;
}
这是可行的,因为如果您将 n!
除以 k!
,您将得到 n = 6 和 k = 4 的结果:
6! 6 * 5 * 4 * 3 * 2 * 1
-- == --------------------- == 6 * 5 == 30
4! 4 * 3 * 2 * 1
您只需取消所有因数 <= k,因此您只需将数字 > k 乘以包括 n。
另请注意,在处理阶乘(或一般非常大的数字)时,最好使用 BigInteger用于您的计算,因为 BigIntegers 不能像 int
或 long
那样溢出。
关于java - 两个阶乘相除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24970913/