Lập trình prolog

Public on June 2, 2014
1: Fibonacci:
domains
       N,K=integer
predicates
       fibo(N,K)
       demo
clauses
       fibo(1,1).
       fibo(2,1).
       fibo(N,K):-N1=N-1,N2=N-2,
                 fibo(N1,K1),fibo(N2,K2),K=K1+K2.
       demo:-write("can tinh so fibonaci thu:"),
             readint(N),
             fibo(N,K),nl,write("ket qua:",K).



2:Phương trình bậc 2:
domains
   A,B,C,D=integer
predicates
   ptb2(A,B,C)
   gbl(A,B,C,D)
clauses
   ptb2(A,B,C):-A=0,B=0,C<>0,write("PTVN").
   ptb2(A,B,C):-A=0,B=0,C=0,write("PTVSN").
   ptb2(A,B,C):-A=0,B<>0,C<>0,X=-C/A,write("PTCN X=",X).
   ptb2(A,B,C):-A<>0,D=B*B-4*A*C,gbl(A,B,C,D).
   gbl(_,_,_,D):-D<0,write("PTVN").
   gbl(A,B,_,D):-D=0,X=-B/(2*A),write("x=",X).
   gbl(A,B,_,D):-D>0,X1=(-B+sqrt(D))/2*A,
                 X2=(-B-sqrt(D))/(2*A),
                 write("X1=",X1),nl,write("X2=",X2).



3: Giai Thừa
predicates
gt(integer,real)
clauses
gt(0,1):-!.
gt(N,K):-N1=N-1,gt(N1,K1),K=N*K1.
goal
clearwindow,
write("Moi ban nhap X:"),
readint(X),
gt(X,K),
write("Giai thu cua ",X," la: ",K)


4:Ước chung lớn nhất

domain

predaicate
ucln(integer, integer, integer)

clauses
ucln(x, y, z):- x>y, t-x-y, ucln(t, y, z).
ucln(x, y, z):- y>x, t= y-x, ucln(x, t, z).
ucln(x, x, x):- write("ucln la: "), write(x).



5:Nguyên tố

predicate
 prime(integer)
clauses
 prime(2):-!
 prime(N):-N>0
 prime(M), M<N, N mod M <>0


6.b.S= 1+1/3+…+1/(2N+1) 

predicates 
tong(integer,integer) 
clauses 
tong(1,1). 
tong(N,T):-N>1,N1=N-1,tong(N1,T1),T=T1+(1/(2N+1)).

7.tính tổng S = 1^2 +2^2....N^n
predicates

mu(integer,integer,integer)
tong(integer,integer)

clauses
mu(X,2,M):-M=X*X.
tong(1,1).
tong(N,T):-N>1,N1=N-1,mu(N,2,M),tong(N1,T1),T=T1+M.

8.tổng danh sách
domains
    dsn=integer*
predicates
    inds(dsn)
    tong(dsn)
clauses
     inds([H|T]):-write(H),nl,inds(T).
     tong([H|T]):-H+tong(T).
goal
     clearwindow,
     inds([3,6,8,10]),
     write("Tong danh sach: ",tong)

9.tổ hợp
predicates
  gt(real,real)
  tohop(real,real,real)
clauses
  gt(0,1):-!.
  gt(N,Kq):-N1=N-1,gt(N1,Kq1),Kq=N*Kq1.
  tohop(N,K,C):-gt(N,Ngt),gt(K,Kgt),Nk=N-K,gt(Nk,Nkgt),C=Ngt/(Kgt*Nkgt).
goal
write("nhap N="),readreal(N),
write("nhap K="),readreal(K),
tohop(N,K,C),
write("to hop chap ",K," cua ",N," la ",C)

10...update...




[Advertising]Faster Thinking - Speed up your brain


Faster Thinking Game



sentiment_satisfied Emoticon