为什么阶乘函数会给我一个负数 OCaml

问题描述 投票:0回答:1

早安,

我正在用 OCaml 测试一些东西,因为我是这门语言的新手。问题是我创建了一个阶乘函数,当然允许我计算阶乘,正如我们所知,阶乘 永远不可能是 < 0。我的代码有时给了我负数……就是这样:

exception FactorialError of string;;
let rec factorial (n: int) : int = (
  if n < 0 then raise (FactorialError "The number has to be upper or equal then 0");
  if n == 0 then 1 else n * factorial(n-1);
);;

let value = ref (1);;
for i = 0 to 100 do
(
  value := factorial i;
  if !value = 0 then raise (FactorialError ("Factorial is no more possible after i = " ^ 
string_of_int i)) else print_string ("i: " ^ string_of_int i);
  print_string "\nValue: ";
  print_int !value;
  print_string "\n";
)
done;;

这里只是其中一些的结果:

i: 0
Value: 1

i: 1
Value: 1

...

i: 20
Value : 2432902008176640000

i: 21
Value : -4249290049419214848 // <- Here is the problem

...这是问题,但不仅是 21 值,还有许多其他...

你有什么想法吗?

提前致谢,

PS:欢迎任何关于升级我的代码的想法。

algorithm math ocaml
1个回答
1
投票

你有一个整数溢出。请注意,

64
位有符号整数必须在

[-9223372036854775808 .. 9223372036854775807]

范围。如果你去 beyond 范围,你会得到 incorrect 价值:

2432902008176640000 * 21 == 51090942171709440000 > 9223372036854775807

如果你想计算 exact 阶乘值,看看 arbitrary precision integer big_int

© www.soinside.com 2019 - 2024. All rights reserved.