javascript - 三元条件求expmod?

标签 javascript sicp

我正在阅读 SICP in JS关于三元条件的非终止示例:

function is_even(n) {
    return n % 2 === 0;
}

function expmod(base, exp, m) {
    const half_exp = expmod(base, exp / 2, m);
    return exp === 0 ? 1
           : is_even(exp) ? half_exp * half_exp % m
           : base * expmod(base, exp - 1, m) % m;
}

console.log(expmod(4, 3, 5))

它解释说:

This would make the function not just inefficient, but actually non-terminating! The problem is that the constant declaration appears outside the conditional expression, which means that it is executed even when the base case exp === 0 is met.

我只是不明白它的想法,当 exp === 0 时,它以 1 终止,但为什么要执行 half_exp?

最佳答案

您在执行的第一行进行递归调用,无论如何。这意味着该函数是非终止的,也就是无限循环。

function expmod(base, exp, m) {
    const half_exp = expmod(base, exp / 2, m); // <- recursive call
    // code ...
}

递归调用应始终与某种检查配对以确保存在退出点。

关于javascript - 三元条件求expmod?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65046009/

相关文章:

javascript - mongoose 与 then 和 catch 链接

scheme - 评估过程是否按正常顺序(方案)进行?

scheme - 评估组合以递归处理 (+ 1 2)

javascript - 如何在 jquery 中获取 viewbag 数据?

javascript - React JS 父子组件事件共享

javascript - jQuery Event.Target 供调用者引用

c - 如何在 C 中实现将名称与 void 函数相关联的映射?

syntax - 不了解 SICP 中的方案程序

emacs - 使用 elisp 实现流

php - 如何在 html/php 中增加变量