Программа на Prolog для определения суммы четных чисел из n первых чисел Фибоначчи:
fib(0, 0). fib(1, 1). fib(N, F) :- N > 1, N1 is N - 1, N2 is N - 2, fib(N1, F1), fib(N2, F2), F is F1 + F2. sum_even_fib(N, Sum) :- sum_even_fib_helper(N, 1, 0, 0, Sum). sum_even_fib_helper(N, Index, PrevFib, PrevPrevFib, Sum) :- fib(Index, Fib), Fib > N, Sum is PrevFib. sum_even_fib_helper(N, Index, PrevFib, PrevPrevFib, Sum) :- fib(Index, Fib), Fib =< N, NewIndex is Index + 1, ( Fib mod 2 =:= 0 -> NewSum is Sum + Fib; NewSum is Sum ), sum_even_fib_helper(N, NewIndex, Fib, PrevFib, NewSum).
Программа на Prolog для определения суммы четных чисел из n первых чисел Фибоначчи:
fib(0, 0).fib(1, 1).
fib(N, F) :-
N > 1,
N1 is N - 1,
N2 is N - 2,
fib(N1, F1),
fib(N2, F2),
F is F1 + F2.
sum_even_fib(N, Sum) :- sum_even_fib_helper(N, 1, 0, 0, Sum).
sum_even_fib_helper(N, Index, PrevFib, PrevPrevFib, Sum) :-
fib(Index, Fib),
Fib > N,
Sum is PrevFib.
sum_even_fib_helper(N, Index, PrevFib, PrevPrevFib, Sum) :-
fib(Index, Fib),
Fib =< N,
NewIndex is Index + 1,
(
Fib mod 2 =:= 0 ->
NewSum is Sum + Fib;
NewSum is Sum
),
sum_even_fib_helper(N, NewIndex, Fib, PrevFib, NewSum).
Пример использования:
sum_even_fib(100, Sum).