PROLOG

Tous les codes de la vidéo

Les collectionneurs

possede(cret,calc(hp71b,1984)).
possede(eric,ordi(zx81,1981)).
possede(ledudu,ordi(c64,1982)).
possede(eric,calc(hp41C,1979)).
possede(nicole,calc(pb100,1983)).
possede(audrey,ordi(apple2,1977)).
possede(cret,ordi(c64,1982)).
possede(ledudu,calc(ti57,1977)).
collection(P):-
 possede(P,ordi(_,_)),
 possede(P,calc(_,_)).

annee(B,H,X):-
    B > H,
    annee(H,B,X).

annee(B,H,X):-
    possede(_,calc(X,A)),
    A =< H,
    A >= B.

annee(B,H,X):-
    possede(_,ordi(X,A)),
    A =< H,
    A >= B. 

?- possede(P,ordi(_,1977)).
?- possede(P,T).
?- possede(_,calc(N,_)).
?- possede(X,calc(_,T)),T<1980.

Nombre d’or

Version 1 :

nombreOr(N, R) :- fc(N, 1, R).
fc(1, A, R) :- R = A.
fc(N, A, R) :-
    S is 1 + 1 / A,
    N1 is N - 1,
    fc(N1, S, R). 

Version 2 :

nombreOr(N, Num, Den) :- fc(N, 1, 1, Num, Den).
 
fc(1, Num, Den, Num, Den).
 
fc(N, NumP, DenP, Num, Den) :-
    N1 is N - 1,
    Num2 is NumP + DenP,
    fc(N1, Num2, NumP, Num, Den).

Taille d’une liste

length([],0).

length([H|T],N):-
    length(T,N1), N is N1+1. 

Triplets pythagoriciens

Version 1 :

valide(A, B, C) :-
    C2 is A*A + B*B,
    C*C =:= C2.

cherche(A, B, C, Max) :-
    between(1, Max, A),
    between(A, Max, B),
    between(B, Max, C),
    valide(A, B, C).

pythagore(Max, R) :-
    findall((A,B,C), cherche(A, B, C, Max), R). 

Version 2 :

entre(B, H, B).
entre(B, H, X) :-
    B < H,
    B1 is B + 1,
    entre(B1, H, X).

valide(A, B, C) :-
    C2 is A*A + B*B,
    C*C =:= C2.

cherche(A, B, C, Max) :-
    entre(1, Max, A),
    entre(A, Max, B),
    entre(B, Max, C),
    valide(A, B, C).

pythagore(Max) :-
    cherche(A, B, C, Max),
    L = [A,B,C],
    write(L), nl,
    fail.

Syracuse

Version 1 :

syr(N):- syr(N,0,N).
syr(1,T,M):- write(T),nl,write(M).
syr(N,T,M):-
 T2 is T + 1,
 suiv(N,T2,M).

suiv(N,T,M):-
 0 is N mod 2,
 N2 is N/2,
 syr(N2,T,M).

suiv(N,T,M):-
 N2 is 3*N+1,
 maxisuiv(N2,T,M).

maxisuiv(N,T,M):- N > M, syr(N,T,N).
maxisuiv(N,T,M):- syr(N,T,M). 

Version 2 :

syr(N):- syr(N,0,N).
syr(1,T,M):- write(T),nl,write(M).
syr(N,T,M):-
 T2 is T + 1,
 suiv(N,N2),
 M2 is max(N,M),
 syr(N2,T2,M2).

suiv(N, N2):-
 0 is N mod 2,
 N2 is N/2,!.

suiv(N, 3 * N + 1).