計算機科学のブログ

Building Abstractions with Functions - Functions and the Processes They Generate - Exponentiation - iterative exponentiation process, successive squaring

Structure and Interpretation of Computer Programs: JavaScript Edition(Harold Abelson(著)、Gerald Jay Sussman(著)、Julie Sussman(著)、The MIT Press)のChapter 1(Building Abstractions with Functions)、1.2(Functions and the Processes They Generate)、1.2.4(Exponentiation)、Exercise 1.16の解答を求めてみる。

コード

function square(x) {
    return x * x;
}
function is_even(n) {
    return n % 2 === 0;
}
function expt(b, n) {
    function iter(n, a) {
        return n === 0 ?
            a :
            is_even(n) ?
                iter(n - 2, square(b) * a) :
                iter(n - 1, b * a);
    }
    return iter(n, 1);
}

console.log(expt(2, 0));
console.log(expt(2, 1));
console.log(expt(2, 2));
console.log(expt(2, 10));
console.log(expt(2, 11));
console.log(expt(2, 100));

入出力結果(Terminal, Zsh)

% node answer1.16.js
1
2
4
1024
2048
1.2676506002282294e+30
%