Hello, I wrote a search for values ​​from the last Fibonacci index. There was an inverse problem. It seems that the recursive algorithm works, put write () and it is clear that the program exits the recursion when it finds the index, but the problem is that I cannot return the found index.

predicates fib2(integer, integer) fibm(integer, integer, integer) clauses fib2(1,1) :- !. fib2(2,1) :- !. fib2(N,F) :- N1 = N - 1, fib2(N1,F1), N2 = N-2, fib2(N2,F2), F = F1+F2. fibm(1, 1, 1) :- !. fibm(2, 1, 1) :- !. fibm(X, N1, Q) :- R = N1 + 1, fib2(R, T), write(" R = ",R), T < X, fibm(X, R), Q = R. goal fibm(21, 0, Q). 

The input is the value from the sequence and you need to return the index of this value.

  • The penultimate goal is a mistake: you must have fibm/3 or fib/2 . - Anton Danilov

1 answer 1

I tried to run your code, correcting it under SWI-Prolog. For the rest, I left almost everything as it is:

  fib2( 1 ,1 ) :- !. fib2( 2 ,1 ) :- !. fib2( N ,F ) :- N1 is N - 1, fib2( N1, F1 ), N2 is N - 2, fib2( N2, F2 ), F is F1 + F2. fibm( 1, 1, 1 ) :- !. fibm( 2, 1, 1 ) :- !. fibm( X, N1, Q ) :- R is N1 + 1, fib2( R, T ), writef(' R = %w',[ R ]), T < X, R = Q, fibm( X, R ). %%% goal :- fibm( 21, 0, Q ), writef('\nQ = %w', [ Q ] ). qoal :- write('no ( more ) solutions.'). :- initialization( goal ). 

Launched, got the result:

R = 1

ERROR : c: /downloads/fib_c.pl: 27: Initialization goal raised exception:

ERROR: fibm / 3: Undefined procedure: fibm / 2

ERROR: However, there are definitions for:

ERROR: fib2 / 2

ERROR: fibm / 3

true

I corrected the code and got this result:

  fib2( 1 ,1 ) :- !. fib2( 2 ,1 ) :- !. fib2( N ,F ) :- N1 is N - 1, fib2( N1, F1 ), N2 is N - 2, fib2( N2, F2 ), F is F1 + F2. fibm( 1, 1, 1 ) :- !. fibm( 2, 1, 1 ) :- !. fibm( X, N1, Q ) :- R is N1 + 1, fib2( R, T ), writef(' R = %w',[ R ]), T < X, R = Q, fibm( X, R, Q ). %%% goal :- fibm( 21, 0, Q ), writef('\nQ = %w', [ Q ] ). qoal :- write('no ( more ) solutions.'). :- initialization( goal ). 

R = 1 R = 2

Warning: c: /downloads/fib_c.pl: 27: Initialization goal failed

true

I hope I could help you.