首页 > 解决方案 > 使用尾递归 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)

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

标签: ocaml

解决方案


提示:你的函数square有类型float -> float并且*是整数乘法。


推荐阅读