Search code examples
prologclpfd

Create a rule in Prolog, cubeLess(X,B,R) which calculates the power of 3 and the remainder such that b =x3+r


I have this question in prolog. Q: Create a rule cubeLess(X,B,R) which calculates the power of 3 and the remainder such that b =x3+r. For an example cubeLess(2,10,R) should result in R=2. So far i have written the base case cubeLess(0,0,0) AND cubeLess(X,B,R) :- X>0, X1 is XXX, How do i go from here?


Solution

  • We assume all numbers of relevance here are integers. With SWI-Prolog, we can use :

    :- use_module(library(clpfd)).
    

    Next, we define predicate cubeLess/3 like this:

    cubeLess(X, B, R) :-
       B #= X^3 + R.
    

    Sample query:

    ?- cubeLess(2, 10, R).
    R = 2.
    

    How about the most general query?

    ?- cubeLess(X, B, R).
    X^3 #= _A,
    _A+R #= B.
    

    Not much propagation here... but that's OK!

    If you are interested in ground solutions, constrain the finite domains and then use labeling/2.