Тема: Повторы и рекурсии
№ 4.6.
Даны натуральное n, действительное x. Вычислить:
%S=sin(x)+sin(sin(x))+sin(sin(sin(x)))... Rekursivnii
predicates
sum(integer,real,real,real)
clauses
sum(0,X,Y,0):- Y=sin(X),!.
sum(N,X, SY, Sum):- NewN=N-1, sum(NewN,X,NewSY,NewSum),
SY=sin(NewSY), Sum=NewSum+NewSY.
goal
N=3, X=2, sum(N, X, _, Sum).
%S=sin(x)+sin(sin(x))+sin(sin(sin(x)))... Iteracionii
predicates
ryad(integer, real, real, real)
ryad(integer, real, real, real,integer, real, real, real)
do
clauses
ryad(N, X, Y, Sum):- ryad(N,X, SinX, Sum, 1, X, Y, Y).
ryad(N,X, SinX, Sum,N,X, SinX, Sum):-!.
ryad(N,X, SinX, Sum, I, X, Sin, NewSum):-
NewI=I+1, NewSin=sin(Sin), NSum=NewSum+NewSin,
ryad(N,X, SinX, Sum, NewI, X, NewSin, NSum).
do:- write("Enter\n"), readint(N), readreal(X), Y=sin(X), ryad(N,X,Y,Sum), write("\n",Sum,"\n").
goal
do.
№ 4.16.
Дано натуральное число n. Вычислить:
S=1!+2!+3!+…+n! (n>1)
%S=1!+2!+3!+4!+...+n! (n>1) Rekyrsivnii
predicates
f(integer, integer)
sum(integer,integer)
clauses
f(1, 1) :- !.
f(FactX,X) :- Y=X-1, f(FactY, Y), FactX = X*FactY.
sum(1, 1) :- !.
sum(N,S):- NewN=N-1, sum(NewN,NewS), f(L,N), S=L+NewS.
goal
N=3, sum(N, S).
%S=1!+2!+3!+4!+...+n! (n>1) Iteracionnii
predicates
f(real, real)
f(unsigned, long, unsigned, long)
sum(integer,real)
sum(integer,real,integer,real)
clauses
f(N, FactN) :- f(N, FactN, 1, 1).
f(N, FactN, N, FactN) :- !.
f(N, FactN, I, P) :- NewI = I+1, NewP = P*NewI, f(N, FactN, NewI, NewP).
sum(N,Sum):-sum(N,Sum,1,1).
sum(N,Sum,N,Sum):-!.
sum(N,Sum,L,S):-L1=L+1,f(L1,P),NewS=S+P,sum(N,Sum,L1,NewS).
goal
X=3,
sum(X, FX).