我的任务是:以自然条件的数量查找正整数的分区数。 例如:N = 5。答案是7,因为5:{1,1,1,1,1},{2,1,1,1},{2,2,1},{3,1,1},{3,2} ,{4,1},{5}
我在JS上写了一个解决方案:
function pcount(number, limit) {
if (limit === 0) {
if (number === 0) {
return 1;
}
return 0;
}
if (limit <= number) {
return pcount(number, limit - 1) + pcount(number - limit, limit);
}
return pcount(number, number);
}
但现在我尝试使用Prolog编写它,但pcount(number, limit - 1) + pcount(number - limit, limit);
语句存在一些困难。
这是我的代码:
PREDICATES
check(integer,integer,integer)
check(integer,integer)
CLAUSES
check(0,0,Result):-
Result=1.
check(_,0,Result):-
Result=0.
check(Number,Limit,Result):-
Limit<=Number,!,
NN=Limit-1,
RR=Number-Limit,
check(Number,NN,Result1),
check(RR,Limit,Result2),
Result=Result1+Result2.
check(A,B):-
check(A,B,X),
write(X).
%check(number, limit - 1) + check(number - limit, limit);
GOAL
check(2,2).
但它不起作用。此谓词出错:check(Number,Limit,Result)
。如何组合两个谓词调用的结果:check(Number, Limit-1)+check(Number-Limit,Limit)
?
答案 0 :(得分:1)
你所拥有的非常接近正确,但需要更多约束。现有子句递归为Limit
的负值。这是一个小问题,应该解决这个问题,以及一些小的调整:
check(0, 0, 1).
check(N, 0, 0) :-
N > 0. % Added constraint N > 0
% avoids overlap with first clause
check(Number, Limit, Result):-
Limit > 0, % Added constraint Limit > 0 avoids overlap
% with first clause and negative values
Limit <= Number, !,
NN = Limit - 1,
RR = Number - Limit,
check(Number, NN, Result1),
check(RR, Limit, Result2),
Result = Result1 + Result2.
check(Number, Limit, Result) :- % Case were Limit > Number as in your
Limit > Number, % original non-Prolog code
check(Number, Number, Result).
check(A, B):-
check(A, B, X),
write(X).