Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

"Bottom-Up" recursive predicates -- Hofstadter Numbers

Status
Not open for further replies.

Regenspaziergang

Programmer
Nov 10, 2007
1
DE
Hello,

I'm currently learning Prolog and just found the "Bottom-up"-way of writing recursive functions, for example for the Fibonacci numbers.
Code:
% Fibonacci: Q(1) = Q(2) = 1
%            Q(n) = Q(n-1) + Q(n-2)
fibo(0, 0).
fibo(1, 1).
fibo(N, Erg) :- 
        N > 1,
        A is N-1, 
        B is N-2, 
        fibo(A, E1), 
        fibo(B, E2), 
        Erg is E1 + E2.
        
% Bottom-Up:
fibo_bu(N, Erg) :- fibo_bu_h(0, 0, 1, N, Erg).
fibo_bu_h(N, Erg, _, N, Erg).
fibo_bu_h(Z, Erg_Z_1, Erg_Z_2, N, Erg) :- 
             Z < N,
             Z_2 is Z + 1,
             Erg_Z is Erg_Z_1 + Erg_Z_2,   
             fibo_bu_h(Z_2, Erg_Z_2, Erg_Z, N, Erg).

Now, I'd like to find a way to program a more efficient Hofstadter algorithm:
Code:
% Hofstadter: Q(1) = Q(2) = 1
%             Q(n) = Q( n - Q(n-1) ) + Q( n - Q(n-2) )
hof(1, 1).
hof(2, 1).
hof(N, Erg) :-
       N > 2,
       M is N-1,
       O is N-2,
       hof(M, X),
       hof(O, Y),
       A is N-X,
       B is N-Y,
       hof(A, E1),
       hof(B, E2),
       Erg is E1 + E2.

As you can see, the numbers are not as easily calculated as the fibonacci numbers, and in particular, you can never quite know which of the previous numbers will be used for the calculation of Q(n). I wonder if it is possible to use a principle like the Bottom-up-recursion on this.

Thank you for your help,

Felix
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top