Created
October 29, 2012 13:48
-
-
Save hoelzro/3973656 to your computer and use it in GitHub Desktop.
Fibonacci sequence implemented in Prolog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
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
What will be the modification required to print the whole series up to the given index?