转到内容

图灵/解法 1

来自维基教科书,开放世界中的开放书籍
var n : int          %User input
var ctr : int := 0   %Counter variable
var gotit : boolean  %Stores if fractorial is found

get n

loop
    ctr := 0  %ctr is NEVER actually used as zero, since that would cause a division by 0 error.

    loop
        gotit := true      %Initially assume that fractorial has been found, and change to false if found otherwise
        ctr += n           %Increase counter by n
        for i : 1 .. n     %Try n/1, n/2, n/3... until n/i.  If all are whole numbers, then answer has been found
            if ctr / i not= ctr div i then
                gotit := false
            end if
        end for
        exit when gotit = true
    end loop

    if gotit = true then
        put "Fractorial (", n, ") = ", ctr
        exit
    end if
end loop

虽然你最初可能尝试 ctr += 1,但很快就会发现这太慢了。通过逻辑推理和一些实验,你应该能够发现 n 的阶乘是 n 的倍数。

华夏公益教科书