我写了这个:
pow :: Integer -> Integer -> Integer
pow x k = if k == 1
then x
else if k `mod` 2 == 0
then pow (x*x) (k `div` 2)
else x * pow (x*x) (k `div` 2)
现在我想编写一个具有给定k
的程序,并决定要执行多少次乘法pow x k
。
我的想法是:
costpow :: Integer -> Integer
costpow 1 = 0
costpow k = if m == 0
then 1 + costpow k
else 2 + costpow k
where ( n , m ) = k `divMod` 2
答案 0 :(得分:2)
这是一个无限循环:
y
您可能需要costpow k = ...
... 1 + costpow k
^^^
之类的内容。
答案 1 :(得分:0)
您的递归将永远不会像其他帖子中所述那样结束。也许你可以简化一点
costpow :: Integer -> Integer
costpow 1 = 0
costpow k = m + 1 + costpow n
where (n,m) = k `divMod` 2