I am reading SICP in JS about a non-terminating example of ternary conditions:
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))
It explains that:
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.
I just cannot get its idea, when exp === 0, it terminate with 1 but why half_exp executed?
from Ternary conditions to find expmod?
No comments:
Post a Comment