找到没有的阶乘它工作正常,但我不明白为什么它给我阶乘 0 表示没有 56、89、77 和其他一些数字
find Factorial of no. It is working fine but i am not able to understand why its giving me factorial 0 for no 56,89,77 and other some numbers
这是我的阶乘程序代码。它工作正常,但我无法理解为什么它给了我阶乘 0 而不是 56、89、77 和其他一些数字。
private static void factorial() {
int resultant = 1, i;
System.out.println("Please Enter any number to find factorial : ");
Scanner scan = new Scanner(System.in);
int fact = scan.nextInt();
for (i = 1; i <= fact; i++) {
resultant = resultant * i;
}
System.out.println("Factorial of number : " + resultant);
}
作为乘积一部分的每个偶数都会为阶乘贡献一个尾随零。实际上,更准确地说,(无限精度)产品的尾随零计数是输入尾随零计数的总和。在有限精度中,尾随零的数量显然受到数字大小的限制。
所以最终,这种情况很快发生,尾随零的数量变得大于或等于 32,在这种情况下,int
的 all 位将为零。同样的事情当然发生在 long
之后,在 64 个尾随零。在此之前的某个时间,即使结果尚未完全为零,它也已经停止匹配无限精度的结果。
比如34!十六进制是
de1bc4d19efcac82445da75b00000000
如果你用 32 位整数计算它,你会得到 8 个最低有效数字,所有这些数字都是零。
你应该知道int
的大小固定为32位。当您的计算结果产生大量无法放入这 32 位的数字时,某些位将会溢出,从而产生错误的结果。您可以尝试使用此代码。
private static void factorial() {
int resultant = 1, i;
System.out.println("Please Enter any number to find factorial : ");
Scanner scan = new Scanner(System.in);
int fact = scan.nextInt();
for (i = 1; i <= fact; i++) {
int test=resultant;
resultant = resultant * i;
if(resultant<test){
system.out.println("Looks like overflow occured");
}
}
System.out.println("Factorial of number : " + resultant);
}
更好的方法是使用 BigInteger
而不是 int
。
如此大的数的阶乘将非常大。您必须使用可以存储非常大的数字的数据类型(我们正在谈论数十亿和万亿)。 BigInteger 数据类型可能有效。试一试。
这是我的阶乘程序代码。它工作正常,但我无法理解为什么它给了我阶乘 0 而不是 56、89、77 和其他一些数字。
private static void factorial() {
int resultant = 1, i;
System.out.println("Please Enter any number to find factorial : ");
Scanner scan = new Scanner(System.in);
int fact = scan.nextInt();
for (i = 1; i <= fact; i++) {
resultant = resultant * i;
}
System.out.println("Factorial of number : " + resultant);
}
作为乘积一部分的每个偶数都会为阶乘贡献一个尾随零。实际上,更准确地说,(无限精度)产品的尾随零计数是输入尾随零计数的总和。在有限精度中,尾随零的数量显然受到数字大小的限制。
所以最终,这种情况很快发生,尾随零的数量变得大于或等于 32,在这种情况下,int
的 all 位将为零。同样的事情当然发生在 long
之后,在 64 个尾随零。在此之前的某个时间,即使结果尚未完全为零,它也已经停止匹配无限精度的结果。
比如34!十六进制是
de1bc4d19efcac82445da75b00000000
如果你用 32 位整数计算它,你会得到 8 个最低有效数字,所有这些数字都是零。
你应该知道int
的大小固定为32位。当您的计算结果产生大量无法放入这 32 位的数字时,某些位将会溢出,从而产生错误的结果。您可以尝试使用此代码。
private static void factorial() {
int resultant = 1, i;
System.out.println("Please Enter any number to find factorial : ");
Scanner scan = new Scanner(System.in);
int fact = scan.nextInt();
for (i = 1; i <= fact; i++) {
int test=resultant;
resultant = resultant * i;
if(resultant<test){
system.out.println("Looks like overflow occured");
}
}
System.out.println("Factorial of number : " + resultant);
}
更好的方法是使用 BigInteger
而不是 int
。
如此大的数的阶乘将非常大。您必须使用可以存储非常大的数字的数据类型(我们正在谈论数十亿和万亿)。 BigInteger 数据类型可能有效。试一试。