計算機科学のブログ

Building Abstractions with Functions - Functions and the Processes They Generate - Example: Testing for Primality - Probabilistic methods - smallest divisor

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.6(Example: Testing for Primality)、Probabilistic methods、Exercise 1.21の解答を求めてみる。

コード

function square(x) {
    return x * x;
}
function smallest_divisor(n) {
    return find_divisor(n, 2);
}
function find_divisor(n, test_divisor) {
    return square(test_divisor) > n ?
        n :
        divides(test_divisor, n) ?
            test_divisor :
            find_divisor(n, test_divisor + 1);
}
function divides(a, b) {
    return b % a === 0;
}

console.log(smallest_divisor(199));
console.log(smallest_divisor(1999));
console.log(smallest_divisor(19999));

入出力結果(Terminal, Zsh)

% node answer1.21.js
199
1999
7
%