Search code examples
prolog

How can I get a list of the powers of X less-than or equal to N in Prolog?


I am trying to learn more about prolog and I want to get a list of the powers of a certain number X less-than or equal to a number N. The result need to be something like this:

?- powers (5,123,List).
List = [25,5,1] ? ;
no

Thanks you so much!


Solution

  • powers(N, MaxP, Lst) :-
        % Start with empty list, to create list in descending order
        powers_(N, MaxP, 1, [], Lst).
        
    powers_(N, MaxP, Upto, LstUpto, Lst) :-
        Upto =< MaxP,
        % Don't backtrack to the "finished" alternative
        !,
        Upto1 is Upto * N,
        % Loop, adding to list in reverse order
        powers_(N, MaxP, Upto1, [Upto|LstUpto], Lst).
    
    % Finished - unify Lst
    powers_(_N, _MaxP, _Upto, Lst, Lst).
    

    Result in swi-prolog:

    ?- time(powers(5, 123, L)).
    % 12 inferences, 0.000 CPU in 0.000 seconds (49% CPU, 216353 Lips)
    L = [25,5,1].