我对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 );
}
}
Run Code Online (Sandbox Code Playgroud)
试试这个:
static int divFactorials (int n, int k) {
int result = 1;
for (int i = n; i > k; i--)
{
result *= i;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
这工作,因为如果你划分n!的k!,你得到这个对于n = 6,K = 4:
6! 6 * 5 * 4 * 3 * 2 * 1
-- == --------------------- == 6 * 5 == 30
4! 4 * 3 * 2 * 1
Run Code Online (Sandbox Code Playgroud)
你只需要取消每个因子<= k,所以你只需要将数字乘以> k到包括n.
另请注意,在使用阶乘(或者通常是大数字)时,最好使用BigInteger进行计算,因为BigIntegers不能像a int或a 那样溢出long.