作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在阅读 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 actuallynon-terminating! The problem is that the constant declaration appearsoutside the conditional expression, which means that it is executedeven 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/
我已经编写了几个用于执行 expmod 的函数,即 (x ** y) % n。这些都是标准函数,我已经检查并重新检查了两者,但找不到任何愚蠢的错误。 这是递归的: def expmod(x,y,m):
下面的程序是用来计算base^expo mod m的。 (define (expmod base expo m) (define (square n) (* n n)) (define
我是一名优秀的程序员,十分优秀!