用 SICStus Prolog 概括斐波那契数列 [英] Generalizing Fibonacci sequence with SICStus Prolog
问题描述
我正在尝试为广义斐波那契数列 (GFS) 的查询找到解决方案.问题是:是否有任何 GFS 的第 12 个数字为 885?前 2 个数字可能被限制在 1 到 10 之间.
I'm trying to find a solution for a query on a generalized Fibonacci sequence (GFS). The query is: are there any GFS that have 885 as their 12th number? The initial 2 numbers may be restricted between 1 and 10.
我已经找到了在从 (1, 1) 开始的序列中找到第 N 个数字的解决方案,其中我明确定义了初始数字.这就是我所拥有的:
I already found the solution to find the Nth number in a sequence that starts at (1, 1) in which I explicitly define the initial numbers. Here is what I have for this:
fib(1, 1).
fib(2, 1).
fib(N, X) :-
N #> 1,
Nmin1 #= N - 1,
Nmin2 #= N - 2,
fib(Nmin1, Xmin1),
fib(Nmin2, Xmin2),
X #= Xmin1 + Xmin2.
对于提到的查询,我认为以下方法可以解决问题,其中我重用 fib 方法而不明确定义初始数字,因为现在需要动态完成:
For the query mentioned I thought the following would do the trick, in which I reuse the fib method without defining the initial numbers explicitly since this now needs to be done dynamically:
fib(N, X) :-
N #> 1,
Nmin1 #= N - 1,
Nmin2 #= N - 2,
fib(Nmin1, Xmin1),
fib(Nmin2, Xmin2),
X #= Xmin1 + Xmin2.
fib2 :-
X1 in 1..10,
X2 in 1..10,
fib(1, X1),
fib(2, X2),
fib(12, 885).
...但这似乎不起作用.
... but this does not seem to work.
这样定义初始数字是不可能的,还是我做错了什么?我不是在寻求解决方案,但任何可以帮助我解决此问题的建议将不胜感激.
Is it not possible this way to define the initial numbers, or am I doing something terribly wrong? I'm not asking for the solution, but any advice that could help me solve this would be greatly appreciated.
推荐答案
在SWI-Prolog下:
Under SWI-Prolog:
:- use_module(library(clpfd)).
fib(A,B,N,X):-
N #> 0,
N0 #= N-1,
C #= A+B,
fib(B,C,N0,X).
fib(A,B,0,A).
task(A,B):-
A in 1..10,
B in 1..10,
fib(A,B,11,885).
这篇关于用 SICStus Prolog 概括斐波那契数列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!