gpt4 book ai didi

prolog - 计算一组不同的奇数(如果存在的话),使得它们的总和等于给定的数字

转载 作者:行者123 更新时间:2023-12-01 23:26:20 25 4
gpt4 key购买 nike

:- use_module(library(clpfd)). % load constraint library

% [constraint] Compute a list of distinct odd numbers (if one exists), such that their sum is equal to a given number.

odd(Num) :- Num mod 2 #= 1.

sumOfList([],N,N) :- !.
sumOfList([H|T],Counter,N) :-
NewN #= H + Counter,
sumOfList(T,NewN,N).

buildOddList(N,InputList,L) :-
%return list when sum of list is N
V in 1..N,
odd(V),
append(InputList,[V],TempL),
sumOfList(TempL,0,N)->
L = TempL;
buildOddList(N,TempL,L).

computeOddList(N) :-
buildOddList(N,[],L),
label(L).

这是我的代码,我似乎无法获得正确的输出,任何代码评论家? :)

最佳答案

这是我对这个问题的看法,通过谓词 nonNegInt_oddPosSummands/2 和辅助谓词 list_n_sum/3 实现:

:- use_module(library(clpfd)).

list_n_sum([],_,0).
list_n_sum([Z|Zs],N,Sum) :-
Z #>= 1,
Z #=< N,
Z mod 2 #= 1,
Sum #= Z + Sum0,
Sum0 #>= 0,
list_n_sum(Zs,N,Sum0).

nonNegInt_oddPosSummands(N,List) :-
length(_,N),
list_n_sum(List,N,N),
chain(List,#<),
labeling([],List).

现在开始一些问题!

首先,“19可以分解成哪些列表?”:

?- nonNegInt_oddPosSummands(19,Zs).
Zs = [19] ;
Zs = [1, 3, 15] ;
Zs = [1, 5, 13] ;
Zs = [1, 7, 11] ;
Zs = [3, 5, 11] ;
Zs = [3, 7, 9] ;
false.

接下来,一个更通用的查询不会终止,因为解决方案集是无限的。 “如果 Zs 的长度为 2,哪些正整数 N 可以分解为 Zs?”

?- Zs=[_,_], nonNegInt_oddPosSummands(N,Zs).
N = 4, Zs = [1,3] ;
N = 6, Zs = [1,5] ;
N = 8, Zs = [1,7] ;
N = 8, Zs = [3,5] ;
N = 10, Zs = [1,9] ...

最后是最一般的查询。与上面的一样,它不会终止,因为解决方案集是无限的。但是,它公平地枚举所有分解和相应的正整数。

?- nonNegInt_oddPosSummands(N,Zs).
N = 0, Zs = [] ;
N = 1, Zs = [1] ;
N = 3, Zs = [3] ;
N = 4, Zs = [1,3] ;
N = 5, Zs = [5] ;
N = 6, Zs = [1,5] ;
N = 7, Zs = [7] ;
N = 8, Zs = [1,7] ;
N = 8, Zs = [3,5] ;
N = 9, Zs = [9] ;
N = 9, Zs = [1,3,5] ;
N = 10, Zs = [1,9] ...

关于prolog - 计算一组不同的奇数(如果存在的话),使得它们的总和等于给定的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1786365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com