English 中文(简体)
幻灯复读法
原标题:Euclidean recursive algorithm

Ok, I know it s really a stupid question, but I can t get it. There is a task where I should find a recursive algorithm of Euclid (gcd). I ve done it for one case, here:

nondeterm nod (integer,integer,integer)
CLAUSES
nod (X,0,X):- !.
nod (0,X,X):- !.
nod (X,0,X):-X>0.
nod (X,Y,G):-Y>0, Z = X mod Y, nod (Y,Z,G).

I need to do another case, where recursion is beginnig from х0, when Xi then calling for function counting Xi+1. It should be sort of it:

PREDICATES
nondeterm nod (integer,integer,integer)
nondeterm nod1 (integer,integer,integer,integer,integer)     
CLAUSES
nod(X,Y,Z):- nod1(X,Y,Z,0,0).   
nod1 (X,Y,Z,X,Y):- Otvet = Z, write("Otvet=", Otvet, "
"), !.
nod1 (X,Y,X,Y):- nod1 (X,Y,X,Y).
nod1 (X,Y,Z,X1,Y1):-
              X1>Y1, X>0, Y>0, 
              Y2 = X1 mod Y1,
              X2 = Y1,
              nod1(X,Y,Z,X2,Y2).

但它没有工作。 请帮助我这样做。

问题回答

The following code works for me. Please note the use of rem, but I guess you could also use mod:

% sys_gcd(+Integer, +Integer, -Integer)
sys_gcd(X, 0, X) :- !.
sys_gcd(X, Y, Z) :-
   H is X rem Y,
   sys_gcd(Y, H, Z).

举例来说,与瑞士妇女发展署-劳工局合作:

?- sys_gcd(20,30,X).
X = 10.
?- sys_gcd(-20,30,X).
X = 10.
?- sys_gcd(20,-30,X).
X = -10.
?- sys_gcd(-20,-30,X).
X = -10.

If you want a particular sign of the result, you need additional code around it.

页: 1





相关问题
Prolog : Learning by example

I am trying to learn a little bit about swi-prolog (beyond the basic, useless programs). Can anyone explain (perhaps in pseudocode) what this sudoku solver and the related functions are doing? If ...

Working with lists in Prolog

First off let me state that this is part of a class exercise given as homework. But, the entire assignment is much more involved than the subject of this question. So.. I am searching through two ...

SWI-Prolog conditional statements

I m trying to write a function that will test to see if the word hello is contained in a list. If it is contained, i don t want it to say "true", i want it to say : "yes, the word hello is contained ...

prolog cut off in method

I have a question I would like to ask you something about a code snippet: insert_pq(State, [], [State]) :- !. insert_pq(State, [H|Tail], [State, H|Tail]) :- precedes(State, H). insert_pq(State, [...

Max out of values defined by prolog clauses

I know how to iterate over lists in Prolog to find the maximum, but what if each thing is a separate clause? For example if I had a bunch of felines and their ages, how would I find the oldest kitty? ...

热门标签