Regenspaziergang
Programmer
Hello,
I'm currently learning Prolog and just found the "Bottom-up"-way of writing recursive functions, for example for the Fibonacci numbers.
Now, I'd like to find a way to program a more efficient Hofstadter algorithm:
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. I wonder if it is possible to use a principle like the Bottom-up-recursion on this.
Thank you for your help,
Felix
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. I wonder if it is possible to use a principle like the Bottom-up-recursion on this.
Thank you for your help,
Felix