我试图获得66号的阶乘值,但是我的方法导致输出0 。 但是每当我尝试获得5的阶乘时,它就会产生120的输出。 任何人都可以告诉我为什么?
public static int factorial(int n) { if (n == 1) return n; return n * factorial(n - 1); }I'm trying to get the factorial value of number 66, but my method resulting me an output 0. But whenever I try to get the factorial of 5, it is resulting me an output 120. Could anyone please tell me why?
public static int factorial(int n) { if (n == 1) return n; return n * factorial(n - 1); }最满意答案
当然 - 因子变得非常大,非常快。 你非常快速地溢出int的范围......并且在某个时刻,你将乘以足够的因子使溢出变为0,然后将该值永远保持为0。
根据谷歌的快速搜索,66阶乘是5.44344939×1092 - 这比int可以处理的要多得多,甚至long或decimal 。 你可能会得到double的处理 - 你会失去大量的精确度,而且会很快积累起来,但至少它不会溢出......
Sure - factorials get very big, very fast. You're overflowing the bounds of int very quickly... and at some point you'll have multiplied by enough factors to get an overflow to 0, which will then keep the value at 0 forever.
According to a quick Google search, 66 factorial is 5.44344939 × 1092 - which is considerably more than int can handle, or even long or decimal. You could get double to handle it - you'd lose a huge amount of precision, and that would accumulate really quickly too, but at least it wouldn't overflow...
因子方法导致错误(factorial method resulting in error)我试图获得66号的阶乘值,但是我的方法导致输出0 。 但是每当我尝试获得5的阶乘时,它就会产生120的输出。 任何人都可以告诉我为什么?
public static int factorial(int n) { if (n == 1) return n; return n * factorial(n - 1); }I'm trying to get the factorial value of number 66, but my method resulting me an output 0. But whenever I try to get the factorial of 5, it is resulting me an output 120. Could anyone please tell me why?
public static int factorial(int n) { if (n == 1) return n; return n * factorial(n - 1); }最满意答案
当然 - 因子变得非常大,非常快。 你非常快速地溢出int的范围......并且在某个时刻,你将乘以足够的因子使溢出变为0,然后将该值永远保持为0。
根据谷歌的快速搜索,66阶乘是5.44344939×1092 - 这比int可以处理的要多得多,甚至long或decimal 。 你可能会得到double的处理 - 你会失去大量的精确度,而且会很快积累起来,但至少它不会溢出......
Sure - factorials get very big, very fast. You're overflowing the bounds of int very quickly... and at some point you'll have multiplied by enough factors to get an overflow to 0, which will then keep the value at 0 forever.
According to a quick Google search, 66 factorial is 5.44344939 × 1092 - which is considerably more than int can handle, or even long or decimal. You could get double to handle it - you'd lose a huge amount of precision, and that would accumulate really quickly too, but at least it wouldn't overflow...
发布评论