Skip to content

Instantly share code, notes, and snippets.

@hoelzro
Created October 29, 2012 13:48
Show Gist options
  • Save hoelzro/3973656 to your computer and use it in GitHub Desktop.
Save hoelzro/3973656 to your computer and use it in GitHub Desktop.
Fibonacci sequence implemented in Prolog
fib(0, 1) :- !.
fib(1, 1) :- !.
fib(N, Result) :- N1 is N - 1, N2 is N - 2, fib(N1, Result1), fib(N2, Result2), Result is Result1 + Result2.
@toderesa97
Copy link

Hi, @Jorgebv02

Brief explanation

You create base cases, and now DEFINE the problem in logical terms.Let's dig into that.... commas (,) represent ANDs.

Remember that the fibonacci sequence is defined recursively, S(n) = S(n-1) + S(n-2) where S(0)=1 and S(1)=1. What we are doing is stating by using predicates that ...

fib(Index, Value) is fib(Index-1, Value1) and fib(Index-2, Value2) and Value = Value1 + Value2.

Obviously at this point, Value1 + Value2 = Value is like saying S(n-1)+S(n-2)=S(n)

How to use it?

Just type on your terminal fib(7,21). or if you want to know the value given an index type the first letter of the param in uppercase fib(7,V).

@rezzycavalheiro
Copy link

I think
fib(0, 1) :- !.
should be
fib(0, 0) :- !.
because the fibonnaci sequence starts with 0 so, if you think about it, fibonacci at index 0 is 0.
For example:
0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 |
Therefore, fibonacci at index 7 is actually 13.

@SoundousBahri
Copy link

when am I supposed to write simple expressions(non recursive) like "N1 is N - 1"and " Result is Result1 + Result2".on the right of the expression and when should it be on the left

@NiharKashyap
Copy link

What will be the modification required to print the whole series up to the given index?

@WodenWang820118
Copy link

WodenWang820118 commented May 21, 2021

fibonacci(0,1):-!. % cut down the backtracking
fibonacci(1,1):-!.
fibonacci(N,X):-
  N > 0, % the constraint to make N always greater than 0; put the integer less than 0 doesn't make sense
  N2 is N - 2, % it doesn't work to pass N-2 into the fibonacci predicate. The "is" is the arithmetic operation, not "=" in other languages 
  N1 is N - 1,
  fibonacci(N2,X2), % get the X2 value
  fibonacci(N1,X1), % get the X1 value
  X is X1 + X2. % calculate the Fibonacci number

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment