使用尾递归OCaml的俄罗斯农民求幂

时间:2019-01-11 02:39:59

标签: ocaml

我尝试了俄罗斯农民指数的无尾递归版本,并且返回如下:

let rec fast_expNTR (base, power) =
  match power with
  |0->1
  |n-> if n mod 2=0 then fast_expNTR (square base, power/2)
      else base * fast_expNTR(square base , power/2)

但是在else base*fast_expNTR(square base , power/2)中,它表示表达式应为float类型,但给出的类型为int。我不明白错误。

此外,这是我对尾递归快速求幂的尝试:

let fast_exp (base , power)=
  let rec helper (acc ,acc2,p)=
    if p=0 then acc * acc2
    else if p mod 2 =0 then helper(int_of_float (square (float_of_int acc)),acc2, p/2)
    else helper(int_of_float(square (float_of_int acc)),acc * acc2, p/2)
  in helper(base,1,power)

但是它没有计算出正确的结果。请帮助

1 个答案:

答案 0 :(得分:1)

提示:函数square的类型为float -> float,而*是整数乘法。

相关问题