prolog中因子分解的数字根和

时间:2015-03-01 14:48:24

标签: prolog

问题在于在用户输入的数字中添加多个可能的因子分解。

我尝试了这段代码。

sum_factors(N,Fs) :-
    integer(N) ,
    N > 0 , 
    setof(F , factor(N,F) , Fs ).

factor(N,F) :-
    L is floor(sqrt(N)),
    between(1,L,X),
    ( F = X ; F is N // X),
    write(F), write('x'), write(X), write('='),
    write(N), nl.
如果输入24,

输出我的代码:

1x1=24
24x1=24
2x2=24
12x2=24
3x3=24
8x3=24
4x4=24
6x4=24
Fs = [1, 2, 3, 4, 6, 8, 12, 24].

如果我输入24应该是正确的输出:

24 = 2x2x2x3
24 = 2x3x4
24 = 2x2x6
24 = 4x6
24 = 3x8
24 = 2x12
24 = 24

有人可以逐行解释这个代码,如果可能的话,告诉我代码中缺少的是什么。

1 个答案:

答案 0 :(得分:0)

尝试这个解决方案,我认为现在已经完成了。

% The first ten prime numbers
% You may want include more, use this URL http://primes.utm.edu/lists/small/1000.txt
prime_numbers([2,3,5,7,11,13,17,19,23,29]).

% Find the lower number in a list of numbers that divide a number N
% We asume that the list of numbers is sorted in ascendent order
lower_splitter(N, [H|_], H):- N mod H =:= 0, !.
lower_splitter(N, [_|T], H):- lower_splitter(N, T, H).

%  Find factors
factors(1, []):- !.
factors(N, [R|L]):- prime_numbers(P), lower_splitter(N, P, R), N1 is N div R, factors(N1, L).

%  Verify is a list contains a subset
sub_set([], []).
sub_set([X|L1], [X|L2]):- sub_set(L1, L2).
sub_set([_|L1], L2):- sub_set(L1, L2).

% Find all subset in the list X.
combinations(X, R):- setof(L, X^sub_set(X, L), R).

% Auxilary predicates
list([]).
list([_|_]).

lt(X,Y):-var(X);var(Y).
lt(X,Y):-nonvar(X),nonvar(Y),X<Y.

difference([],_,[]).
difference(S,[],S):-S\=[].
difference([X|TX],[X|TY],TZ):-
   difference(TX,TY,TZ).
difference([X|TX],[Y|TY],[X|TZ]):-
   lt(X,Y),
   difference(TX,[Y|TY],TZ).
difference([X|TX],[Y|TY],TZ):-
   lt(Y,X),
   difference([X|TX],TY,TZ).

%Multiply members of a list
multiply([X], X):-!.
multiply([H|T], X):-multiply(T, M), X is M *H.

start(N):-  factors(N, L),
            setof(R, L^S^T^D^M^(sub_set(L, S),
                   length(S, T),
                   T>1,difference(L, S, D),
                   multiply(S,M),
                   append(D,[M], R)), F), writeall(N,[L|F]).

writeall(_,[]).
writeall(N,[H|T]):- write(N),write('='),writelist(H),nl, writeall(N,T).

writelist([X]):- write(X).
writelist([X,Y|T]):-  write(X),write(x), writelist([Y|T]).

使用start谓词进行咨询,如下所示:

?- start(24).
24=2x2x2x3
24=2x2x6
24=2x3x4
24=2x12
24=3x8
24=24