Search code examples
prologpredicatebacktracking

Function in prolog with backtracking


The function is

backtracking function f(n,k)

or

f(n, k) = n * k,           if n = k
        = n ∗ f(n−1, k),   if n > k
        = k ∗ f(n,   k−1), if n < k

The Prolog predicate fn/3 assign in order to implement the above function

Can you help me solve the above function? Thank you


Solution

  • You can try with the below predicates.

    f(N, K, R):-
        N = K ,
        R is N*K,!.
    
    f(N, K, R):-
        N>K,
        Nx is N-1,
        f(Nx,K,Res),
        R is N*Res.
    
    f(N, K, R):-
        N<K,
        Kx is K-1,
        f(N,Kx,Res),
        R is K * Res.
    

    The R will have the result that you wanted.