Turing/Solution 1

From Wikibooks, open books for an open world
Jump to navigation Jump to search
var n : int          %User input
var ctr : int := 0   %Counter variable
var gotit : boolean  %Stores if fractorial is found

get n

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

        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
    end if
end loop

While you might try ctr += 1 initially, it will quickly become evident that this is too slow. Through logical reasoning and some experimentation, you should be able to discover that the fractorial of n is a multiple of n.