我知道這個答案不完全的OP回答這個問題(我getPrimeList(N, L)
創建從零到N
所有質數的列表L
;在OP要求第一個N
素數),但......只是爲了好玩......我試圖實施Eratosthenes篩。
getListDisp(Top, Val, []) :-
Val > Top.
getListDisp(Top, V0, [V0 | Tail]) :-
V0 =< Top,
V1 is V0+2,
getListDisp(Top, V1, Tail).
reduceList(_, _, [], []).
reduceList(Step, Exclude, [Exclude | Ti], Lo) :-
NextE is Exclude+Step,
reduceList(Step, NextE, Ti, Lo).
reduceList(Step, Exclude, [H | Ti], [H | To]) :-
Exclude > H,
reduceList(Step, Exclude, Ti, To).
reduceList(Step, Exclude, [H | Ti], [H | To]) :-
Exclude < H,
NextE is Exclude+Step,
reduceList(Step, NextE, Ti, To).
eratSieve([], []).
eratSieve([Prime | Ti], [Prime | To]) :-
Step is 2*Prime,
Exclude is Prime+Step,
reduceList(Step, Exclude, Ti, Lo),
eratSieve(Lo, To).
getPrimeList(Top, []) :-
Top < 2.
getPrimeList(Top, [2 | L]) :-
Top >= 2,
getListDisp(Top, 3, Ld),
eratSieve(Ld, L).
我再說一遍:不是真的答案;只是爲了好玩(就像OP,我試圖學習Prolog)。
[Prolog查找N個素數]的可能重複(http://stackoverflow.com/questions/12446407/prolog-find-n-prime-numbers) – Prune